Hello,
I have a recursive function that I would like to rewrite into an iterative one. To illustrate, lets say I have a struct
struct SomeStruct { pub value: i32 }
and a function
fn get_other(s: &mut SomeStruct) -> Option<SomeStruct>
{
if s.value == 1 {
Some(SomeStruct{value: 2})
}
else {
None
}
}
I now have a function that uses get_other that I would like to rewrite. The recursive version:
fn do_something_recursive(s : &mut SomeStruct) {
//Do something with s...
println!("{}", s.value);
//Get next value
if let Some(mut other) = get_other(s) {
do_something_recursive(&mut other);
return;
}
}
I tried to rewrite it as
fn do_something_iterative(s : &mut SomeStruct) {
let mut s = &s;
loop {
//Do something with s...
println!("{}", s.value);
//Get next value
if let Some(mut other) = get_other(*s) {
s = &&mut other;
}
else {
return;
}
}
}
But failed to get that working. I would appreciate a nudge into the right direction.
Thanks!
Alex