问题
This code compiles:
struct IntDisplayable(Vec<u8>);
impl fmt::Display for IntDisplayable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for v in &self.0 {
write!(f, "\n{}", v)?;
}
Ok(())
}
}
fn main() {
let vec: Vec<u8> = vec![1,2,3,4,5];
let vec_Foo = IntDisplayable(vec);
println!("{}",vec_Foo);
}
whilst this code doesn't:
struct StrDisplayable(Vec<&str>);
impl fmt::Display for StrDisplayable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for v in &self.0 {
write!(f, "\n{}", v)?;
}
Ok(())
}
}
fn main() {
let vec: Vec<&str> = vec!["a","bc","def"];
let vec_Foo = StrDisplayable(vec);
println!("{}",vec_Foo);
}
error message:
error[E0106]: missing lifetime specifier
--> src/lib.rs:3:27
|
3 | struct StrDisplayable(Vec<&str>);
| ^ expected lifetime parameter
What I'm trying to do is to implement fmt::Display
for a Vec<&str>
, which generally required wrapping Vec
like this, however it only works for Vec<u8>
, why substitute Vec<u8>
into Vec<&str>
led to such compile error?
回答1:
The compiler is told that you're borrowing a value, but not for how long it will live. Should it be static? Something else?
I presume you're trying to do the following.
struct StrDisplayable<'a>(Vec<&'a str>);
This way, you're explicitly telling the compiler that the strings will live at least as long as the struct, no less.
You'll also need to add in a lifetime in the implementation of the trait, which can by anonymous if using Rust 2018.
来源:https://stackoverflow.com/questions/57266481/why-is-vecstr-missing-lifetime-specifier-here