Skip to content

Instantly share code, notes, and snippets.

@JEG2
Created August 21, 2014 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JEG2/ae7746544cef14be1606 to your computer and use it in GitHub Desktop.
Save JEG2/ae7746544cef14be1606 to your computer and use it in GitHub Desktop.
An exploration of the concept of lifetimes.
// I'm trying to make sure I have my head around "lifetimes"
// after a few readings of the guide:
// http://doc.rust-lang.org/guide-lifetimes.html. The following is
// a simple example of what I think I now know that I'll try to explain
// in this comment.
//
// Because the letters are "borrowed references," (Do I have my terms right?)
// they could potentially be freed before the Lists struct that contains them.
// Since this possibility exists, Rust requires the explicit lifetime 'a which
// indicates that the lifetime of a created Lists instance is tied to whatever
// references were passed into the letters slot.
#[deriving(Show)]
struct Lists<'a> {
numbers: Vec<int>,
letters: Vec<&'a str>
}
fn main() {
let lists = Lists{numbers: vec![1, 2, 3], letters: vec!["A", "B", "C"]};
println!("{}", lists);
}
@steveklabnik
Copy link

Your comments are basically correct. There's one or two minor subtleties, but the overall point is right.

I would write this code like this, though:

#[deriving(Show)]
struct Lists {
    numbers: Vec<int>,
    letters: Vec<String>
}

fn main() {
    let lists = Lists{
        numbers: vec![1, 2, 3],
        letters: vec!["A".to_string(), "B".to_string(), "C".to_string()]
    };
    println!("{}", lists);
}

Because we use a String rather than a &str, the List has ownership of all of the references it contains, and so we don't need the lifetimes. We do need to add the .to_string() calls to turn the &static str literals into Strings, though. This is kinda ugly, we're working on it.

@steveklabnik
Copy link

(this is one reason all of the way we teach lifetimes is changing. it's really more about ownership than about lifetimes. rust-lang/rust#16487 just got merged, and will appear in the docs tonight, it might be more clear)

@Dr-Emann
Copy link

I'd say the choice of whether to use a String / &str should be made based on the needs of the struct. As you said, it comes down to ownership, if a Lists struct logically owns its letters, it should hold Strings, but there are definite cases when a struct should only have references to things owned by someone else.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment