I want to enter a loop with a variable n
which is borrowed by the function. At each step, n
takes a new value; when exiting the loop, the job is done, with the help of other variables, and n
will never be used again.
If I don't use references, I have something like this:
fn test(n: Thing) -> usize {
// stuff
let mut n = n;
for i in 1..10 {
let (q, m) = n.do_something(...);
n = m;
// stuff with x
}
x
}
x
is the result of some computation with q
and m
but it is an usize
type and I didn't encounter any issue in this part of the code. I didn't test this code, but this is the idea. I could make code written like this work.
Since I want to do it with a reference; I tried to write:
fn test(n: &Thing) -> usize {
// stuff
let mut n = n;
for i in 1..10 {
let (q, m) = (*n).do_something(...);
n = &m;
// stuff with x
}
x
}
Now the code will not compile because m
has a shorter lifetime than n
. I tried to make it work by doing some tricky things or by cloning things, but this can't be the right way. In C, the code would work because we don't care about what n
is pointing to when exiting the loop since n
isn't used after the loop. I perfectly understand that this is where Rust and C differ, but I am pretty sure a clean way of doing it in Rust exists.
Consider my question as very general; I am not asking for some ad-hoc solution for a specific problem.