String's lifetime when returning Vec<&str> [duplicate]

前提是你 提交于 2020-03-16 06:13:04

问题


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:


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


来源:https://stackoverflow.com/questions/33855809/strings-lifetime-when-returning-vecstr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!