(done) 速通 rustlings(9) 分支跳转

RUST 中的分支跳转-条件判断不需要加括号

rust 复制代码
fn picky_eater(food: &str) -> &str {
    if food == "strawberry" {
        "Yummy!"
    } else if food == "potato" {
        "I guess I can eat that."
    } else {
        "No thanks!"
    }
}

RUST 作为一种表达式导向的语言,if-else 块作为一个表达式,可以直接赋值给变量:

rust 复制代码
fn animal_habitat(animal: &str) -> &str {
    // TODO: Fix the compiler error in the statement below.
    let identifier = if animal == "crab" {
        1
    } else if animal == "gopher" {
        2
    } else if animal == "snake" {
        3
    } else {
        4
    };

    // Don't change the expression below!
    if identifier == 1 {
        "Beach"
    } else if identifier == 2 {
        "Burrow"
    } else if identifier == 3 {
        "Desert"
    } else {
        "Unknown"
    }
}
相关推荐
shimly1234568 小时前
(done) 速通 rustlings(4) 变量声明
rust
shimly1234569 小时前
(done) 速通 rustlings(11) 向量vector及其操作
rust
shimly1234569 小时前
(done) 速通 rustlings(3) intro1 println!()
rust
shimly1234569 小时前
(done) 速通 rustlings(12) 所有权
rust
shimly12345611 小时前
(done) 速通 rustlings(7) 全局变量/常量
rust
敲敲了个代码11 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
开发语言·前端·javascript·后端·rust
lpfasd12311 小时前
Tauri 中实现自更新(Auto Update)
rust·tauri·update
shimly12345611 小时前
(done) 速通 rustlings(10) 基本数据类型
rust
shimly12345611 小时前
(done) 速通 rustlings(8) 函数
rust