Rust conditional statement


Release date:2023-11-07 Update date:2023-11-07 Editor:admin View counts:243

Label:

Rust conditional statement

Conditional statements in the Rust language are in this format:

Example

fn main() {
    let number = 3;
    if number < 5 {
        println!("Condition is true");
    } else {
        println!("Condition is false");
    }
}

There are conditions in the above procedure if statement, this syntax is common in many other languages, but there are some differences: first, conditional expressions number < 5 does not need to be included in parentheses (note that it is not allowed); but in Rust if there is no single sentence. {} is not allowed to use a statement instead of a block Nonetheless, Rust supports traditional else-if grammatical:

Example

fn main() {
    let a = 12;
    let b;
    if a > 0 {
        b = 1;
    }
    else if a < 0 {
        b = -1;
    }
    else {
        b = 0;
    }
    println!("b is {}", b);
}

Running result:

b is 1

Conditional expressions in Rust must be bool type, for example, the following program is incorrect:

Example

fn main() {
    let number = 3;
    if number {   // Error reporting,expected \`bool`, found integerrustc(E0308)
        println!("Yes");
    }
}

Although conditional expressions in the Cripple + language are expressed as integers, either 0 or true, this rule is prohibited in many languages that pay attention to code security.

Combined with the function body expressions learned in the previous chapter,we associate them with:

if <condition> { block 1 } else { block 2 }

Can the { block 1 } and { block 2 } in this syntax be function body expressions?

The answer is yes! That is, in Rust, we can use the if-else structure to implement expressions similar to ternary conditional operations (A ? B : C) effect:

Example

fn main() {
    let a = 3;
    let number = if a > 0 { 1 } else { -1 };
    println!("number 为 {}", number);
}

Running result:

number is 1

Note: both function body expressions must be of the same type! And there must be one else and the expression blocks that follow.

Powered by TorCMS (https://github.com/bukun/TorCMS).