4

Simple code:

fn foo() -> Vec<&'static str> {

    let mut vec = Vec::new();
    let mut string = String::new();

    // doing something with string...

    vec.push(string.as_str());

    return vector; // error here: string doesn't live long enough
}

I have problem that I need to process with string and return it in Vec as str. Problem is that binding string doesn't live long enough, since it goes out of scope after foo. I am confused and I don't really know how to solve that.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Rišo Baláž
  • 75
  • 1
  • 4

1 Answers1

2

A &'static str is a string literal e.g. let a : &'static str = "hello world". It exists throughout the lifetime of the application.

If you're creating a new String, then that string is not static!

Simply return a vector of String.

fn foo() -> Vec<String> {

    let mut vec = Vec::new();
    let mut string = String::new();

    // doing something with string...

    vec.push(string);

    return vec;
}

fn main() {
    foo();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
W.K.S
  • 9,787
  • 15
  • 75
  • 122
  • Hello, thank you, changing String to str helped, so str has same methods as String? Am I right? – Rišo Baláž Nov 22 '15 at 14:43
  • 1
    @RišoBaláž, it's more like that `String` has the same methods as `str` and more, because there is a `Deref` implementation for `String`. See [here](https://doc.rust-lang.org/stable/book/strings.html) (at the bottom) and [here](https://doc.rust-lang.org/stable/book/deref-coercions.html). – Vladimir Matveev Nov 22 '15 at 15:51
  • Idiomatically, you wouldn't use `return vec`, you'd just end the method with `vec`. – Shepmaster Nov 22 '15 at 17:44