我希望能夠將Chars
迭代器指定給結構,該結構的String
是在結構的「構造函數」方法內部創建的。我該怎麼做呢?無法返回Chars迭代器,因爲它「不夠長」
碼(run it):
use std::str::Chars;
fn main() {
let foo = Foo::new();
}
struct Foo<'a> {
chars: Chars<'a>
}
impl<'a> Foo<'a> {
pub fn new() -> Self {
let s = "value".to_string();
Foo { chars: s.chars() }
}
}
錯誤:
error: `s` does not live long enough
--> <anon>:13:22
13 |> Foo { chars: s.chars() }
|> ^
note: reference must be valid for the lifetime 'a as defined on the block at 11:25...
--> <anon>:11:26
11 |> pub fn new() -> Self {
|> ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 12:36
--> <anon>:12:37
12 |> let s = "value".to_string();
|>
(在我真正的代碼,構造從文件中讀取文本)
有[** 84個問題標記鏽**](http://stackoverflow.com/search?q=%5Brust%5D+%22does+not+live+long+enough%22+is%3Aq)與確切的字符串「活得不夠長」。作爲一個具有18k +聲望的堆棧溢出用戶,您應該[知道顯示您在提問之前執行的研究](http://meta.stackoverflow.com/q/261592/155423)爲新人到現場。 – Shepmaster
正如Shepmaster所說,已經有84個問題解釋了這個錯誤信息;你能否解釋一下你的情況所欠缺的細節,以便答案可以根據你的情況而定製,而不是一個通用的「這是怎麼回事」? –