fn main() {
let strings = vec![String::from("hello")];
let default = String::from("default");
let s = first_or(&strings, &default);
println!("{}", s);
}
fn first_or(strings: &Vec<String>, default: &String) -> &String {
if strings.len() > 0 {
&strings[0]
} else {
default
}
}
我尝试返回
&strings[0]
或 default
,但错误仍然存在。我不想知道如何解决这个错误,但是这段代码的具体部分导致了这个错误,为什么?
在 Rust 中,所有引用都有生命周期。如果您总是必须写出这些生命周期,那会很烦人,因此编译器通常可以弄清楚您想要什么。这就是所谓的终身埃利森。
// Notice how you don't have to write out the lifetimes.
fn elided(s: &str) -> &str {
s
}
// This function does the exact same thing, but the lifetimes are spelled out explicitly.
fn explicit<'a>(s: &'a str) -> &'a str {
s
}
但是,在您的示例中,编译器无法执行此操作。据编译器所知,
strings
和default
可能有不同的生命周期。为了编写你的函数,你需要明确地阐明生命周期。
// note that `strings` and `default` both have the same lifetime as the output
fn first_or<'a>(strings: &'a Vec<String>, default: &'a String) -> &'a String {
if strings.len() > 0 {
&strings[0]
} else {
default
}
}
有关更详细的解释,请参阅 Rust 书的有关生命周期 elison 的部分。