String's lifetime when returning Vec<&str>

2020-04-11 08:00发布

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.

1条回答
干净又极端
2楼-- · 2020-04-11 08:35

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();
}
查看更多
登录 后发表回答