Biela Diela
Biela Diela

Reputation: 727

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

I am trying to code an Excel-like data structure:

use std::collections::HashMap;

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

fn main() {}

but I am getting an error:

error[E0106]: missing lifetime specifier
 --> src/main.rs:4:22
  |
4 |     columns: HashMap<&str, Vec<f64>>,
  |                      ^ expected lifetime parameter

Can someone help me understand what's going on?

Upvotes: 46

Views: 40939

Answers (2)

evilone
evilone

Reputation: 22740

"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>>
}

Upvotes: 52

Yilmaz
Yilmaz

Reputation: 49190

Reference to the struct field should live as long as the structure itself lives. Because we do not want to have a structure with a reference field which is pointing to an invalid resource. For example

struct Person<'a>{
    name:&'a str,
    age:i32,
}
fn main(){
  let first_name="yilmaz";
  let mut person=Person{
    name:&first_name,
    age:32
  };
  {
    let last_name=String::from("bingol");
    // `last_name` does not live long enough
    // borrowed value does not live long enough
    person.name=&last_name;
  }
  // If I remove the print, code will have no issue
  println!("person name is {} and his age is {}",person.name,person.age)
}

in println! Person struct is still live but last_name does not live long enough, its scope is over inside code block and yet we are trying to access it inside the pirntln!

Upvotes: 4

Related Questions