我有这个代码:
let fd = libc::creat(path, FILE_MODE);
if fd < 0 {
/* error */
}
C 中的等价物更短:
if ((fd = creat(path, FILE_MODE)) < 0) {
/* error */
}
我可以在 Rust 中做类似的事情吗?我试图将它映射到 if let
但它看起来像是在处理 Option
。
最佳答案
不,设计上是不可能的。 let
绑定(bind)是 one of the two non-expression statements在 rust 中。这意味着绑定(bind)不会返回任何可以进一步使用的值。
一般来说,绑定(bind)作为表达式在 Rust 中没有多大意义。考虑 let s = String::new()
: 这个表达式不能返回 String
,因为 s
拥有字符串。或者 let (x, _) = get_tuple()
呢? ?表达式会返回整个元组还是只返回未忽略的元素?所以 ⇒ let
绑定(bind)不是表达式。
关于 if let
: 可悲的是,这也行不通。它只是让我们能够测试解构是否有效,或者换句话说:解构一个可反驳的模式。这不仅适用于 Option<T>
, 但所有类型。
如果你真的想缩短这段代码,有一个方法:make c_int
很容易转换成更惯用的类型,比如 Result
.这最好通过扩展特征来完成:
trait LibcIntExt {
fn to_res(self) -> Result<u32, u32>;
}
impl LibcIntExt for c_int {
fn to_res(self) -> Result<u32, u32> {
if self < 0 {
Err(-self as u32)
} else {
Ok(self as u32)
}
}
}
有了这个你可以使用if let
结果 Result
:
if let Err(fd) = libc::creat(path, FILE_MODE).to_res() {
/* error */
}
关于rust - 我可以将变量赋值与 if 结合使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38239073/