0

I was working in coding dojo trying to learn Rust. In the attached link is all our code and test. However, we got stumped as to why we required calling clone() in one function but not the other.

Why do I need to call game.clone() on line 23 of lib.rs in this link https://cyber-dojo.org/kata/edit/WvEB5z

pub fn say_game_score(game: Game) -> String { if game.player1.score == game.player2.score { return say_equal_score(game.player1.score); } if can_be_won(game) { // This line required game.clone() WHY??? return say_winning_situation(game); // This line does NOT require game.clone() } return format!( "{} {}", say_score_name(game.player1.score), say_score_name(game.player2.score) ); } fn say_winning_situation(game: Game) -> String { if game.player1.score > game.player2.score { return say_leading_situation(game.player1.name, game.player1.score - game.player2.score); } else { return say_leading_situation(game.player2.name, game.player2.score - game.player1.score); } } fn can_be_won(game: Game) -> bool { return game.player1.score > FORTY || game.player2.score > FORTY; } 

1 Answer 1

2

can_be_won(game) causes the variable game to be moved into the function. When you then call say_winning_situation(game) the variable has already moved and cant be used anymore. The Rust compile can actually check these things.

The compiler suggests that you clone the game in the first invocation, so it will be copied instead of moved.

You probably want to use references instead of values in your functions. Only take ownership when you need it. For reading access a reference (which is const by default) is your first choice.

You should read about borrow checking in Rust.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.