I'm making a Tic-Tac-Toe game in Rust as a beginners project and was working on calculation the state of the game(won, draw, etc.) when I ran into this issue. I first wrote the following code:
fn status(&self) -> Status {
if Board::has_won(self.x_board) {
Status::Won(true)
} else if Board::has_won(self.o_board) {
Status::Won(false)
} else if self.is_full() {
Status::Draw
} else {
Status::None
}
}
I then modified it to return a refrence:
fn status(&self) -> &Status {
if Board::has_won(self.x_board) {
&Status::Won(true)
} else if Board::has_won(self.o_board) {
&Status::Won(false)
} else if self.is_full() {
&Status::Draw
} else {
&Status::None
}
}
I did this to link the lifetime of self and the returned value together so if the state of the board changed the reference to status could no longer be used.
I then tried this code:
fn status(&self) -> &Status {
let status;
if Board::has_won(self.x_board) {
status = Status::Won(true)
} else if Board::has_won(self.o_board) {
status = Status::Won(false)
} else if self.is_full() {
status = Status::Draw
} else {
status = Status::None
}
&status
}
And it resulted in a compiler error saying it cannot return a referenced to owned data. Why doesn't the first snippet have this issue?