Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...