Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a while loop evaluate to a value?

Tags:

loops

rust

I'm learning Rust and today I stumbled upon being able to assign variables through if/else expressions. For instance:

let y = 5;

let x = if y > 20 { 20 } else { y };

Is there some way to do this with a while loop? I tried:

fn main() {
    let mut n = 0;

    let mut num = 0;

    num += while n < 10 {
        n += 1;
        5
    };
}

with the hope that num would eventually be equal to 50, with the while loop incrementing num by five each iteration, but I get the following error

error[E0308]: mismatched types
 --> src/main.rs:8:9
  |
8 |         5
  |         ^ expected (), found integral variable
  |
  = note: expected type `()`
             found type `{integer}`

error[E0277]: cannot add-assign `()` to `{integer}`
 --> src/main.rs:6:9
  |
6 |     num += while n < 10 {
  |         ^^ no implementation for `{integer} += ()`
  |
  = help: the trait `std::ops::AddAssign<()>` is not implemented for `{integer}`

Naturally, I could put the num += 5 inside the while loop, but that takes the fun out of it.

This is my first day with Rust, so I don't even know if it's possible to do what I have in mind. Is this indeed possible? Am I making a syntax error?

This is another version of the code I'm trying to run, but also fails to work:

fn main() {
    let mut num = 0;

    num += while num < 50 {
        5
    };
}
like image 240
mjkaufer Avatar asked Mar 01 '15 19:03

mjkaufer


1 Answers

No. The value of a while loop is always (), the unit type.

RFC 1624 did enhance loop loops to be able to break with a value:

let x = loop {
    break 42;
};
println!("{}", x);
like image 115
Shepmaster Avatar answered Nov 15 '22 11:11

Shepmaster