Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust cannot return value referencing local variable [duplicate]

Tags:

rust

I guess this is a quite basic Rust question, but I have this piece of code

struct Stock<'a> {
    name: &'a str,
    value: u8,
}
impl<'a> Stock<'a> {
    fn read(file: &mut File) -> Stock<'a> {
        let mut value = vec![0; 1];
        file.read(&mut value);
        let name_size = read_u32(file);
        let mut name = vec![0; name_size as usize];
        file.read(&mut name);
        return Stock {
            name: str::from_utf8(&name).unwrap(),
            value: value[0],
        };
    }
}

and of course, it doesn't work, because I am referencing a local value name. To my limited knowledge, this is because outside the scope of read, name doesn't exist. However wouldn't from_utf8 create a new variable that is not scoped to read?

Also, I've read a bit about other people with this issue, and the suggestion is always to switch to the owned String. But why can't I do something such as name: str::from_utf8(&name).unwrap().to_owned()?

like image 789
munHunger Avatar asked Oct 20 '25 08:10

munHunger


1 Answers

However wouldn't from_utf8 create a new variable that is not scoped to read?

No, it gives you a borrow with the same lifetime as the one you pass.

Even if it created a new variable, you would have to tie it to somewhere, like the scope of read(), so again you would have the same problem.

The issue is that your Stock struct holds a reference. That means whatever it points to it has to live for all the time Stock is alive. But any variables you create in the local scope of read() will die when read() ends.

Instead, what you want is for Stock to own the value so that it keeps alive it itself.

like image 62
Acorn Avatar answered Oct 22 '25 02:10

Acorn



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!