我正在使用下面的代码,它可以工作,但显然不是一个非常聪明或有效的方式来写一个值到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";
}
};
根据单位文档
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 ()
去掉分号应该会阻止value被丢弃,这样&str
就可以从if
块中解析出来。
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")
};