I’m doing a match statement like this:
let command: u32 = match command.trim().parse() {
Ok(num) => {
num
},
Err(_) => {}
}
But this whole thing is in a loop {}
How do I break out of the loop and also return the num?
I’ve been trying something like this:
let command: u32 = match command.trim().parse() {
Ok(num) => {
num;
break 'inner;
}
}
But that doesn’t return anything because of the semicolon. And if I switch the break and num, the num is unreachable. So how do I combine these two?
This is the whole code:
for n in players {
println!("It's {}s turn", n.name);
'inner: loop {
println!("Input 1 to throw the dice");
let mut command = String::new();
io::stdin()
.read_line(&mut command)
.expect("Failed to read line");
let command: u32 = match command.trim().parse() {
Ok(num) => {
num;
break 'inner;
}
Err(_) => {
println!("You need to input 1 to throw");
continue 'inner;
}
};
}
}
Thanks a lot!
>Solution :
Even without that, it wouldn’t work, because your println statement return () which you cannot assign to u32. Even if it succeeded, the lifetime of command is limited to the loop so you can’t use it after breaking out.
For your particular problem, I think the break val syntax can help you :
let command: u32 = loop {
println!("Input 1 to throw the dice");
let mut command = String::new();
io::stdin()
.read_line(&mut command)
.expect("Failed to read line");
match command.trim().parse::<u32>() {
Ok(res) => break res,
Err(_) => println!("invalid")
};
};