【发布时间】:2020-04-20 10:56:04
【问题描述】:
我已经在 Rust 上进行了一段时间的试验。 Rust 中的生命周期存在一些混淆。请看下面的代码:
fn main() {
let string1 = String::from("abcd");
let result;
{
let string2 = "xyzvn";
result = longest(string1.as_str(),string2);
}
println!("The Longest String is {}",result);
}
fn longest<'a>(x: &'a str,y:&'a str) -> &'a str{
if x.len() >y.len(){
x
}
else{
y
}
}
string2 的生命周期在内部作用域之后结束,结果在外部作用域中定义。当在 println! 中传递结果时,编译不会报错,继续打印结果。 但是,当我将 string2 更改为:
let string2 = String::from("xyzvd");
借用检查器会抱怨。为什么会这样。
【问题讨论】:
标签: rust