问题描述
此代码编译:
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);
}
此代码没有:
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[E0106]: missing lifetime specifier
--> src/lib.rs:3:27
|
3 | struct StrDisplayable(Vec<&str>);
| ^ expected lifetime parameter
我想做的是为 Vec<& str>
实施 fmt :: Display
,这通常需要包装 Vec 代码>,例如此,但是它仅适用于
Vec< u8>
,为什么将 Vec< u8>
替换为 Vec<& str>
会导致这种编译错误?
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?
推荐答案
编译器被告知您正在借用一个值,但是没有使用该值多久.它应该是静态的吗?还有吗?
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.
您还需要延长特质的实现期限,如果使用Rust 2018,则可以匿名添加.
You'll also need to add in a lifetime in the implementation of the trait, which can by anonymous if using Rust 2018.
这篇关于为什么Vec& str>这里缺少生命周期说明符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!