Lifetimes - noob question

I have code like this:

let lines: Vec<String>;  // actually read from a file 

for line in lines{
    module.parse(&line);
}

(My module.parse looks like:

impl<'a> Module<'a>{
  pub fn parse(&mut self, line: &'a str){

The problem is that my module needs a lifetime for the &str but the borrow occurs within the braces, so I get that the borrowed value doesn't live long enough.

Thanks in advance,

Alan

You should also share the definition of the Module<'a> struct. And maybe in the first code example show the place where the module variable is defined.


As for solutions, either Module might need to be changed to store owned string values.

Or, if borrowing from lines for the module.parse calls is possible without lifetime problems, then changing the loop to for line in &lines might help, which iterates over references to the lines items that are a bit longer lived than in your code example, but of course still limited to the lifetime of the lines variable.

You've probably put a reference — a temporary scope-bound loan — inside the Module struct, instead of an owning type (e.g. &str rather than String).

References in structs prevent structs from storing the data, and make the structs themselves temporary views. This is an advanced feature that makes use of the structs very difficult or outright impossible, and it's not the same thing as "storing by reference" from other languages (in Rust the Box type is that kind of reference).

Don't use references in structs until you're an advanced Rust programmer. If the compiler tells you to add <'a> treat it as a red flag and back out.


However, if you really want Module to be a view into lines and work only inside that one function, then don't consume the lines in the loop and borrow them instead:

for line in &lines {
    module.parse(line);
}

@steffahn and @kornel - y'all are awesome. Changing it to for line in &lines completely fixed my issue.

In the past I have avoided lifetimes but am now trying to understand them.

Thanks a lot!!

--Alan

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.