-3

I want to be able to assign a Chars iterator to a struct, whose String was created inside of the struct's "constructor" method. How do I do this?

Code (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:

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();
   |>        

(In my real code, the constructor reads text from a file)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael
  • 34,873
  • 17
  • 75
  • 109
  • 8
    There are [**84 questions tagged rust**](http://stackoverflow.com/search?q=%5Brust%5D+%22does+not+live+long+enough%22+is%3Aq) with the exact string `does not live long enough`. As a Stack Overflow user with 18k+ reputation, you should [know to show the research you have performed before asking the question](http://meta.stackoverflow.com/q/261592/155423) to set a good example for people new to the site. – Shepmaster Jul 24 '16 at 20:45
  • 2
    As Shepmaster said, there are already 84 questions explaining this very error message; could you explain what detail they lacked for your situation so that the answer can be tailored to your case instead of being a generic "that's just how it is"? – Matthieu M. Jul 25 '16 at 12:43

1 Answers1

5

You can't. Chars does not take ownership of the string, so once you go out of Foo::new, the string does not exist anymore. You need to store the string itself. Chars really is just a small utility type that's meant to be used on site, not stored somewhere to be used later.

mcarton
  • 27,633
  • 5
  • 85
  • 95
  • 3
    See also [Return local String as a slice (&str)](http://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str) - `Chars` [contains a slice](https://github.com/rust-lang/rust/blob/1.10.0/src/libcore/str/mod.rs#L326-L328). – Shepmaster Jul 24 '16 at 21:04