最近我正在学习所有权和终生。但我发现字符串文字的情况很奇怪。
//! work perfectly
fn foo() -> &'static str {
let a = "66";
&a
}
fn main() {
let b = foo();
println!("{}", b);
}当我像上面一样使用字符串文字时,当我像下面这样使用字符串时,它会工作perfectly.But:
//! broken
fn main() {
{
let b;
{
let a = "66";
b = &a;
}
println!("{}", b);
}
}它坏了,告诉我:
b = &a;
^^ borrowed value does not live long enough这些让我很困惑。他们为什么不一样?
请帮帮我,非常感谢。
发布于 2022-01-16 14:06:15
这两个程序之间的区别来自于自动取消引用。
//! work perfectly
fn foo() -> &'static str {
let a = "66";
&a // the type of this expression is not &'static str it is &&'static str
}
fn main() {
let b = foo();
println!("{}", b);
}因为a的类型是&'static str,所以&a的类型是&&'static str。注意第二个引用。它是对没有静态生存期的字符串的引用,而不是字符串值的引用。但是,由于foo的返回类型为&'static str,所以&a被自动取消引用到a,并且b的类型被推断为&'static str。在第二个程序中,这种情况不会发生,因为类型不是显式的,所以b被推断为一个&&'static str,它引用的是一个只存在于块生命周期的引用。
如果第二个程序被更新以显式声明b的类型,您将得到同样的效果。
但是,更好的方法是根本不依赖于自动取消引用,并使用以下两个程序之一:
fn foo() -> &'static str {
let a = "66";
a // note no &
}
fn main() {
let b = foo();
println!("{}", b);
}或
fn main() {
{
let b;
{
let a = "66";
b = a; // Again no &
// In idiomatic code it would probably make sense to inline the
// assignment, but I have left it in for clarity with the original code
}
println!("{}", b);
}
}https://stackoverflow.com/questions/70730274
复制相似问题