I am new to Rust. It would be nice if someone could help me. The first code works, but not the second one.
#![allow(unused)]
fn main() {
let y = 3;
println!("{} Liftoff!", countdown(y));
}
fn countdown(mut y: u8) -> u8 {
let coun = loop {
println!("{}", y);
y -= 1;
if y == 1 {
return (y);
}
};
}
I thought while or for give back a value automatically.
How can I give back a value in while or for loop?
#![allow(unused)]
fn main() {
let y = 3;
println!("{} Liftoff!", countdown(y));
}
fn countdown(mut y: u8) -> u8 {
while y != 0 {
y -= 1;
}
}
/*fn countdown () -> u8{
for y in (1..4).rev(){
}
}*/
CodePudding user response:
- Loops are expressions in rust. This means that you can write
let x = loop { /* ... */ };. However in your first snippet you do not return value from the loop (that you are trying to assign tocoun), but are instead returning from the function. You could rewrite it to be like this:
fn countdown (mut y:u8)-> u8 {
loop {
println!("{}",y);
y-=1;
if y==1 {
break y;
}
} // notice the lack of semicolon here!
}
Here you have a loop that returns a u8 (as en expression) and then this value is returned from the function.
You return value from loop expression by using
breakstatement. In your second snippet there is nobreak, so thiswhileloop returns a unit type(). Since this is the last expression in the function rust tries to return it, and gives you an error, since you said that this function should returnu8, but you are trying to return(). To fix this "problem" you could add abreakstatement however this would be odd to use awhileloop like that.forloop is very different fromloopandwhile. You should think of it as for each. You can still usecontinueandbreakstatements. However you cannot usebreakwith a value.forloop must always evaluate to().
Bonus
Did you know that you can give loops labels? This is very useful when you have nested loops (for example when you have main game loop and inside it a loop for event queue). This means that you can write code that looks like this:
let test = false;
let test2 = true;
let x = 'outer: loop {
'inner: loop {
if test {
break 'outer 42;
} else if test2 {
continue 'inner;
} else {
continue 'outer;
}
}
};
You can read detailed documentation about loop expressions and loop labels here.
