Appearance
生命周期2:exercises/lifetimes/lifetimes2.rs
题目
rust
// lifetimes2.rs
//
// So if the compiler is just validating the references passed to the annotated
// parameters and the return type, what do we need to change?
//
// Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is '{}'", result);
}
题目解析
请记住,通用的生命周期'a
将获得等于x
和y
生命周期中较小者的具体生命周期。
在main
函数中,string1
的生命周期一直到函数结尾,但是string2
的生命周期在longest
函数运行结束,}
的地方就结束了。此时如果result
结果是string2
,那么最后一行输出时,因为string2
生命周期已经结束,已经被销毁,那么就是在读取一个不存在的数值。修改方法有两种:
第一种,让string1
和string2
生命周期一样长。
rust
fn main() {
let string1 = String::from("long string is long");
let result;
let string2 = String::from("xyz");
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is '{}'", result);
}
第二种,在string2
生命周期到期前进行输出:
rust
fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
println!("The longest string is '{}'", result);
}
println!("The longest string is '{}'", result);
}