-
Notifications
You must be signed in to change notification settings - Fork 13.3k
docs: "You’ll also need explicit lifetimes when working with structs" :o #29742
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I'm not sure, that entire chapter seems lacking. "structs can also have lifetimes" but they don't, they can have lifetime parameters, which are just like type parameters, except lifetimes instead of types. struct values have lifetimes (in the other sense, of "liveness"), which new users may confuse with the lifetime parameters of a struct. |
I've just realized that lifetime specifier is required when using struct Foo<'a> {
x: &'a i32,
} I guess that sentence isn't completely false after all. So, this won't work: struct Foo2 {
x: &i32,
}
but this will: struct Foo2 {
x: i32,
} For completion:
struct Foo { x: &bool } // error
struct Foo<'a> { x: &'a bool } // correct
enum Bar { A(u8), B(&bool), } // error
enum Bar<'a> { A(u8), B(&'a bool), } // correct
type MyStr = &str; // error
type MyStr<'a> = &'a str; // correct
// error, no input lifetimes
fn foo() -> &str { ... }
// error, `x` and `y` have distinct lifetimes inferred
fn bar(x: &str, y: &str) -> &str { ... }
// error, `y`'s lifetime is inferred to be distinct from `x`'s
fn baz<'a>(x: &'a str, y: &str) -> &str { ... }
|
Lifetime parameters for structs are never implicit. But some structs have no lifetime parameters. |
You’ll also need explicit lifetimes when working with structs:
from here: https://doc.rust-lang.org/nightly/book/lifetimes.html#in-structs
That seems to say that you always need explicit lifetimes when working with structs, but, that's not true, is it? A quick peek ahead at structs, and lifetimes seem to be implicit there: https://doc.rust-lang.org/nightly/book/structs.html
This
As you can see, structs can also have lifetimes.
also made me realize I'm misinterpreting the above sentence.EDIT: Ok but now I'm not sure again, there's that
need
again:So why do we need a lifetime here? We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.
The text was updated successfully, but these errors were encountered: