我有這樣的簡單的例子:從字符串轉換爲&STR具有不同壽命
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創建一個引用並將其擴展到生命週期'a,因爲String是堆分配?
可能重複[爲什麼我不能返回從字符串生成的&str值?](http://stackoverflow.com/questions/29781331/why-cant-i-return-an-str-value-generated -from-a-string) – malbarbo 2016-05-26 22:12:58