I'm new to Rust, and wanna write some simple game.
In the code below I have some peace of code, where I define riddler and guesser between 2 players of the game.
enum PlayerMovingPosition{
Riddler,
Guesser,
}
struct Player {
name: String,
moving_position: Option<PlayerMovingPosition>,
}
struct Game {
player1: Player,
player2: Player,
}
fn define_riddler_n_guesser(&self) {
let mut riddler: &Player;
let mut guesser: &Player;
for player in [&self.player1, &self.player2] {
match player.moving_position {
Some(PlayerMovingPosition::Riddler) => riddler = player,
Some(PlayerMovingPosition::Guesser) => guesser = player,
_ => panic!("Hey damba, player {} moving position is undefined!", player.name.as_str()),
}
//... Place where I got the error
}
I've got the E0381 error, that says that the variables may be unitialized there.
I went through some searching and got condractiory answers, like:
- some people claimed that it's bad practice to declare variables without initializing it, and it leads to bugs; they adviced to use some iterationg magic I can't get now cause of my poor rust skill.
- others said that it's a proper way, and is used in situations like:
let lol;
{
lol = "kek";
}
println!(lol);
// kek
I found it contoversial and I can't decide what to do in my case, but I bet they aren't contradictiory, they are about different things, and I can't see this difference due to poor understanding.
It would be fine if you tell me if I wrote bad code in rust and show me the right one