官术网_书友最值得收藏!

  • Rust Programming By Example
  • Guillaume Gomez Antoni Boucher
  • 151字
  • 2021-07-02 19:12:57

Writing a condition

Similar to other languages, Rust conditions are expressed with the if and else keywords:

let number1 = 24;
let number2 = 42;
if number1 > number2 {
    println!("{} > {}", number1, number2);
} else {
    println!("{} <= {}", number1, number2);
}

However, they do not require parentheses around the conditional expression. Also, this expression must be of the bool type: you cannot use a number as you would in other languages.

One particularity of Rust conditions, like many other constructs, is that they are expressions. The last expression of each branch is the value of this branch. Be careful though, the type of each branch must be the same. For instance, we can get the minimum number of the two numbers and put it into a variable:

let minimum =
    if number1 < number2 {
        number1
    } else {
        number2
    }; // Don't forget the semi-colon here.
主站蜘蛛池模板: 西平县| 远安县| 平果县| 舟曲县| 沙坪坝区| 茶陵县| 遵化市| 重庆市| 遂宁市| 如皋市| 平远县| 祁门县| 和硕县| 建平县| 青川县| 浦北县| 贺兰县| 阳泉市| 郎溪县| 玛沁县| 壶关县| 莲花县| 开封县| 丹江口市| 乳山市| 汉沽区| 启东市| 神池县| 罗甸县| 舟曲县| 惠州市| 大理市| 裕民县| 湖北省| 合肥市| 白城市| 蒙山县| 克什克腾旗| 辛集市| 鲁山县| 如东县|