Home > database >  While Loop Or For Loop In Other Functions in RUST
While Loop Or For Loop In Other Functions in RUST

Time:10-10

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:

  1. 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 to coun), 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.

  1. You return value from loop expression by using break statement. In your second snippet there is no break, so this while loop 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 return u8, but you are trying to return (). To fix this "problem" you could add a break statement however this would be odd to use a while loop like that.

  2. for loop is very different from loop and while. You should think of it as for each. You can still use continue and break statements. However you cannot use break with a value. for loop 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.

  • Related