English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Rust Conditional Statements

The conditional statements in Rust language are in this format:

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

In the above program, there is a conditional if statement, which is very common in many other languages, but there are also some differences: first, the conditional expression is number < 5 It is not necessary to use parentheses to enclose (note that it is not forbidden, not not allowed); However, Rust does not have the rule that a single statement does not need to be enclosed in {} without adding {}, and it is not allowed to use a single statement to replace a block. Despite this, Rust still supports traditional else-if statement syntax:

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 of bool type, for example, the following program is incorrect:

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

Although C/C++ In the language, the conditional expression is represented by integers, 0 is false, 1 is true, but this rule is prohibited in many languages that pay attention to code safety.

Combining the function body expressions learned in the previous chapter, we can associate them:

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

the syntax of this is { block 1 } and { block 2 } Can it be a function body expression?

The answer is affirmative! That is to say, in Rust, we can use if-else structure implementation is similar to the ternary conditional expression (A ? B : C) Effect:

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

Running Result:

number is 1

NoteThe types of two function body expressions must be the same! And there must be an else and its subsequent expression block.