Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rust, work around: cannot return value referencing local variable [duplicate]

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.

like image 801
Rišo Baláž Avatar asked Aug 29 '26 01:08

Rišo Baláž


1 Answers

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();
}
like image 177
W.K.S Avatar answered Aug 31 '26 05:08

W.K.S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!