Returning a structure containing mutable values

I have the following code where I am trying to return a struct Foo with a set of default values ​​for the values field. These values ​​may be changed later. But the compiler complains:

 error: `initial` does not live long enough 

How can this be achieved? Any alternatives?

 struct Foo <'a> { values: &'a mut Vec<i32>, } impl <'a> Foo <'a> { fn new() -> Foo <'a> { let initial = vec![1, 2]; Foo { values: &mut initial } } } let my_foo = Foo::new(); my_foo.values.push(3); 
+7
rust
source share
1 answer

There are two problems here.

First, you do not need to use &mut to change the structure field. The mutation is inherited in Rust. That is, if you have Foo stored in a mutable variable ( let mut f: Foo ), its fields are mutable; if it is in an immutable variable ( let f: Foo ), its fields are immutable. The solution is to simply use:

 struct Foo { values: Vec<i32>, } 

and return the value Foo by value.

The second problem (and the source of the actual compilation error) is that you are trying to return the loan to what you created in this function. It's impossible. No, there is no way around this; you cannot extend the life of the initial somehow returning initial , and the loan will not work. Indeed. This is one of the things that Rust has been specifically designed to absolutely ban.

If you want to transfer something from a function, one of two things must be true:

  • It is stored somewhere outside the function that will survive the current call (for example, you were given a loan as an argument, the return is not taken into account) or

  • You are returning the property, not just the borrowed link.

Corrected Foo works because it owns Vec<i32> .

+17
source share

All Articles