Created
August 21, 2014 14:20
-
-
Save JEG2/ae7746544cef14be1606 to your computer and use it in GitHub Desktop.
An exploration of the concept of lifetimes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
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
(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)