#Evaluate a variable only when its used

18 messages · Page 1 of 1 (latest)

dark zephyr
#

I want to get a mutable reference to something in a bigger struct because i use that reference a lot. The obvious solution is to create a variable for that. But sometimes I need to pass a mutable reference to the struct to a function, which causes 2 mutable references to be created. Which is not allowed in rust.

Heres an example:

let reference = &mut big_struct.thing.unwrap().get_mut(blahblah).unwrap();
let thing = my_function(&mut big_struct); // Not allowed
reference.modify(thing);

The solution to this is to only evaluate a variable only when its used. Like this:

let thing = my_function(&mut big_struct);
// &mut big_struct has expired and it can be referenced again
big_struct.thing.unwrap().get_mut(blahblah).unwrap().modify(thing);

But this causes the original problem to be an issue again. So is there a cleaner way to do this? Sorry if this doesn't make much sense.

upper mulch
#

The general solution is to rethink your design so you don't need overlapping mutable references.

The easy solution is sometimes just to get the same variable twice in the same function, so you don't hold it across another function call

dark zephyr
upper mulch
#

This looks like you're passing the same argument twice, but it's hard to be sure

#

That is, you appeaar to have written code where modify receives a reference to (overlapping parts of) thing from multiple arguments

pulsar ether
#

@dark zephyr I think your example is slightly too abstract.

dark zephyr
#

why?

upper mulch
dark zephyr
#

ok i'll update the example with some more info

#

It's more like this

let reference: &mut String = &mut big_struct.thing.unwrap().get_mut(blahblah).unwrap();
let thing = my_function(&mut big_struct); // Not allowed
reference.push_str(format!("{thing}").as_str());
upper mulch
upper mulch
#

If so, whatever, it doesn't really matter:

let thing = my_function(&mut big_struct).to_string();
let reference: &mut String = &mut big_struct.thing.unwrap().get_mut(blahblah).unwrap();
reference.push_str(&thing);
#

(to_string is a shorthand for format!("{}"))

dark zephyr
#

ik but i want to reuse the reference

upper mulch
#

The easy solution is just to not reuse it, and instead use my_function again later