Reputation: 397
I am trying to receive some input, and then either return the value if it's valid or get input again if it's not. However, I'm running into borrow checker issues trying to both check the value and return it (new to Rust). Here's the code snippet:
fn get_move(&self) -> (String, String) {
let player = self.current_player();
let mut mv;
let mut is_valid = false;
loop {
mv = player.make_move();
{
is_valid = self.move_valid(mv);
}
match is_valid {
true => return mv,
_ => continue,
}
}
}
fn move_valid(&self, (_from,_to): (String, String)) -> bool {
false
}
Error returned is
error[E0382]: use of moved value: `mv`
--> src/game.rs:75:32
|
72 | is_valid = self.move_valid(mv);
| -- value moved here
...
75 | true => return mv,
| ^^ value used here after move
|
= note: move occurs because `mv` has type `(std::string::String, std::string::String)`, which does not implement the `Copy` trait
I tried adding the scope around self.move_valid
, but it the move_valid
method still appears to be owning mv
when I try and return it.
Is there a standard Rust pattern for repeated input until the value is valid? How can I get this to work?
Upvotes: 0
Views: 1003
Reputation: 5305
When you just pass an unadorned parameter (like (String,String)
) to a function, you are moving the value into that function. You don't have it anymore, you've given it to the function.
You probably just want to change the parameter type to &(String,String)
to pass a reference instead. Then the function will be able to look at the data, but no ownership change will take place.
Upvotes: 1