Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 657
Biela Diela Avatar asked Nov 02 '15 19:11

Biela Diela


1 Answers

"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>>
}
like image 199
evilone Avatar answered Oct 28 '22 21:10

evilone