rust 使用枚举通过if let块重构变量赋值

kokeuurv  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(175)

我正在使用下面的代码,它可以工作,但显然不是一个非常聪明或有效的方法来写入一个值到res

let mut res = "";
if let Video(n) = res_info {    // res_info represents reference to &Settings type
    if n.pixel_width > 1920{
         res = "2160p";
    }
    else{
        res = "1080p";
    }
}

打印res_info将产生以下结果:

Video(Video { pixel_width: 1920, pixel_height: 1080})

下面的代码看起来很接近,但是它没有将&str赋值给res。我更喜欢这样的代码块,其中res只声明了一次。

let res = if let Video(n) = res_info {
    if n.pixel_width > 1920 {
        "2160p";
    }
    else{
        "1080p";
    }
};
yvfmudvl

yvfmudvl1#

根据unit文档
The semicolon ; can be used to discard the result of an expression at the end of a block, making the expression (and thus the block) evaluate to ()
删除分号应阻止值被丢弃,以便从if块中解析&str

let res = if let Video(n) = res_info {
    if n.pixel_width > 1920{
         "2160p"
    } else{
        "1080p"
    }
}else{
    panic!("res_info is not a Video")
};

或者使用match语句可能更简洁

let res = match res_info {
    Video(n) if n.pixel_width > 1920 => "2160p",
    Video(n) => "1080p",
    _ => panic!("res_info is not a Video")
};

相关问题