What does “missing lifetime specifier” mean when storing a &str in a structure?

“Missing lifetime specifier” means that in the struct definition, you haven’t told it how long the reference to the string slice is allowed to stay around. In order for your code to be safe, it has to stick around for at least as long as the struct.

You need to define a lifetime parameter on your struct and use it for the string slice.

struct Excel<'a> {
    columns: HashMap<&'a str, Vec<f64>>
}

This says that string slice (the HashMap key) has some lifetime parameterized by the user of the Excel struct. Lifetimes are one of the key features of Rust. You can read more about lifetimes in Rust documentation.

Usually it’s simpler to define a struct that owns the string. Then you can use String.

struct Excel {
    columns: HashMap<String, Vec<f64>>
}

Leave a Comment