Rewrite recursive function into iterative

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

You just need to store other somewhere so it isn't dropped before the mutable reference to it is dropped.

fn do_something_iterative(s : &mut SomeStruct) {
    let mut other;
    let mut s = &mut *s;
    loop {
        //Do something with s...
        println!("{}", s.value);

        //Get next value
        if let Some(new_other) = get_other(s) {
            other = new_other;
            s = &mut other;
        }
        else {
            return;
        }
    }
}
1 Like