从字符串转换为具有不同生命周期的& str [英] Converting from String to &str with a different lifetime
问题描述
我有一个简单的例子:
fn make_string<'a>() -> &'a str {
let s : &'static str = "test";
s
}
fn make_str<'a>() -> &'a str {
let s : String = String::from_str("test");
s.as_slice()
}
fn main() {
println!("{}", make_string());
println!("{}", make_str());
}
错误消息:
<anon>:8:9: 8:10 error: `s` does not live long enough
<anon>:8 s.as_slice()
^
<anon>:6:34: 9:6 note: reference must be valid for the lifetime 'a as defined on the block at 6:33...
<anon>:6 fn make_str<'a>() -> &'a str {
<anon>:7 let s : String = String::from_str("test");
<anon>:8 s.as_slice()
<anon>:9 }
<anon>:6:34: 9:6 note: ...but borrowed value is only valid for the block at 6:33
<anon>:6 fn make_str<'a>() -> &'a str {
<anon>:7 let s : String = String::from_str("test");
<anon>:8 s.as_slice()
<anon>:9 }
error: aborting due to previous error
playpen: application terminated with error code 101
Program ended.
似乎借位检查器认识到静态寿命比" a长,因此make_string的转换有效,但make_str失败.因为String是堆分配的,所以有没有办法从String创建引用并将其扩展到生存期'a?
It seems that the borrow checker recognizes that 'static is a greater lifetime than 'a so the conversion for make_string works, but make_str fails. Is there a way to create a reference from String and extend it to lifetime 'a, since String is heap allocated?
推荐答案
这里有一个基本的误解:String
未分配堆.
There is a fundamental misconception here: String
is not heap allocated.
String
的 content 是堆分配的,但是其生存期与String
对象本身的生存期相关联,并且每当String
被删除时(在此处结尾) make_str
),那么String
的内容也会被删除.
The content of String
is heap allocated, but its lifetime is tied to the lifetime of the String
object itself, and whenever String
is dropped (here, at the end of make_str
), then the content of String
is dropped too.
因此,编译器是正确的:结果String::as_slice
的生存期小于或等于String
的生存期,并且String
的生存期以该函数结束...因此,您无法返回对的引用.它.
Therefore, the compiler is right: the lifetime of the result String::as_slice
is less than or equal to that of String
and the lifetime of String
ends with the function... thus you cannot return a reference to it.
这篇关于从字符串转换为具有不同生命周期的& str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!