3. If-Else

by anonymous · 2026-06-01 07:22:39 · 22 views

Basic If-Else

fn main() {
    let num :i8 = 5;
    if num == 5  {
        println!("Hello, world!");
    } else {
        println!("This must not be executed!");
    }
}

Simple. If num==5, it must print "Hello, World!". And let num :i8 = 5; is present. There is no difference at interpretation. When compiling this, rustc compiler will remove this branch; as a result the source will actually behave like this.

fn main() {
    println!("Hello World!");

Yet it's simple.

Expression

Rust supports if-else as an expression.

Consequently, the result will look like this...

fn main() {
    let condition = true;
    // if condition is true, it assigns 5. if condition is false, it assigns 6.
    let number = if condition { 5 } else { 6 }; 
    println!("number: {}", number);
}

Simple? Yeah, but I guess this may corrupt the team's code style like Ternary operator, or goto. But as you know those two are sometimes good for the team's code convention(like how my ex-laboratory used goto to tidy embedded linux codes). At least, conditon is a constant so you cannot modify it after it is decided. This is way better than C language's const, you can determine whether to put specific value or not.

Pattern Matching

Please look carefully. As your next step will be match expression.

fn main() {
    let some_option = Some(3);
    if let Some(i) = some_option {
        println!("Some({})", i);
    } else {
        println!("This must not be executed.");
    }
}

Same as:

#include <stdio.h>
#include <stdbool.h>

typedef struct { bool is_some; int value; } Option;

int main() {
    Option some_option = { .is_some = true, .value = 3 };

    if (some_option.is_some) {
        int i = some_option.value; 
        printf("Some(%d)\n", i);
    } else {
        printf("This must not be executed.\n");
    }
}

Simple, Nah. But, looks safer. As many Modern C code lines use this pattern.

Impressions

Safe? Yes. Fast? Yes. Easy? Nah...I don't think so.

Back

Comments

No comments yet.