I finished Chapter 10 in the book (Generic Types, Traits, and Lifetimes). I still do not understand how lifetimes works with structs. I tried to find, if somebody already asked about this on this forum. And it is. But the more I read, the less I understood.
In the book there only one example (apart from impl examples), and it looks like this:
struct ImportantExcerpt<'a> {
part: &'a str,
}
This annotation means an instance of
ImportantExcerptcan’t outlive the reference it holds in itspartfield.
Okay. I'm understand how syntax looks like. But what it's possible to describe with it, apart this case? And how to read such syntax, when it's describing something, that is not this case? And what problem is being solved at all? Usage of this struct in example is straightforward:
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let i = ImportantExcerpt {
part: first_sentence,
};
}
When I thought about this, I realized that I'm also not sure about something more basic about structs, outside of theme with lifetimes. Is the following statement correct?
It is possible to declare and initialize struct variable separately, but when initializing such variable, it's necessary to initialize all its fields right away. It's impossible to delay initializing of some fields.