Modifying a value inside a loop with a function that takes ownersip of the value

Viewed 61

I would like to alter the value of a variable inside a loop using a function that takes ownership of the value that is to be modified and returns a new value of the same type. What I've tried thus far is something like the following:

struct Value;

fn modify (val: Value) -> Result<Value, &'static str> {
  
  // Pseudocode
  match val {
    valid => return Ok(val),
    not_valid => return Err("An error occurred")
  }
}


fn modify_until_err (val: Value) -> Value {
  
  let mut value = val;

  loop {
    let temp = match modify(value) {
      Ok(val) => val,
      Err(e) => break
    };
    value = temp;
  };

  value

}

With this setup I get the error

use of moved value `value`

I get that modify eats up the value, but if I reassign temp to value, why is the compiler still complaining?

1 Answers

The compiler is complaining because when you use break, you haven't assigned a new value to value, but you still try to return it.

There are multiple ways to get around this issue:

  • Modify the mogrify function to return ownership of something that you would want to return from the loop
  • Pass val by mutable reference instead of passing ownership
  • Clone the value to return later
Related