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

  • 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.
主站蜘蛛池模板: 静安区| 琼中| 乐平市| 个旧市| 开封县| 昔阳县| 临西县| 高州市| 伊吾县| 公安县| 朝阳市| 左贡县| 鄂尔多斯市| 绥滨县| 民勤县| 泰兴市| 监利县| 望谟县| 台北市| 荔浦县| 武威市| 张掖市| 红河县| 绥德县| 泾阳县| 西乌珠穆沁旗| 莒南县| 宿迁市| 宣化县| 黑河市| 墨江| 沧州市| 精河县| 延庆县| 闸北区| 饶阳县| 于田县| 双桥区| 琼结县| 平邑县| 米泉市|