2016-07-24 31 views
-2

我希望能夠將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(); 
    |>   

(在我真正的代碼,構造從文件中讀取文本)

+7

有[** 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

+1

正如Shepmaster所說,已經有84個問題解釋了這個錯誤信息;你能否解釋一下你的情況所欠缺的細節,以便答案可以根據你的情況而定製,而不是一個通用的「這是怎麼回事」? –

回答

5

你不能。 Chars不接受字符串的所有權,所以一旦你離開Foo::new,字符串不再存在。你需要存儲字符串本身。 Chars真的只是一個小型的實用程序類型,意在在現場使用,而不是存儲在某個地方以備後用。

+2

請參閱[返回本地字符串作爲切片(&str)](http://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str) - 'Chars' [包含切片] (https://github.com/rust-lang/rust/blob/1.10.0/src/libcore/str/mod.rs#L326-L328)。 – Shepmaster

相關問題