Conditionals in Rust

Conditionals in Rust

Introduction

So let's learn about how to create if-else statements in Rust.

Examples

fn main() {
    let x = 10;
    if x < 5 {
        println!("Small");
    } else {
        println!("Big");
    }
}

In the above Code snippet. Output will be Big.

One thing to note in Rust is that the condition x < 5 in this case, should always be boolean.

let x = 5;
if x {
    println!("x exists");
}

This will throw an error. Unlike JavaScript where we have the concept of truthy & falsy values. There x will be automatically converted to bool when used in a condition.

fn main() {
    let x = 10;
    if x < 5 {
        println!("Small");
    } else if x < 15 {
        println!("Medium");
    } else {
        println!("Big");
    }
}

Now we can also add an else if. In this case the output will be Medium.

We can also write if else statements in one-line.

fn main() {
    let condition = 5 > 15;
    let y = if condition {2} else {4};
    println!("{y}");
}

Output will be 4. Because condition is false.

One-thing to note is both values of y should be of same type.

fn main() {
    let condition = 5 > 15;
    let y = if condition {2} else {"four"};
    println!("{y}");
}

This will throw an error.

error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:3:36
  |
3 |     let y = if condition {2} else {"four"};
  |                           -        ^^^^^^ expected integer, found `&str`
  |                           |
  |                           expected because of this

For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` (bin "guessing_game") due to previous error

The error message is very clear. if & else have incompatible types.

Conclusion

That's all you need to know about Conditionals in Rust. We will discuss about Loops in the next article. Cheers!