我正在尝试在 Rust 中使用 match
。我写了一个函数:
fn main() {
let try = 3;
let x = match try {
Some(number) => number,
None => 0,
};
}
但是我得到了错误:
error[E0308]: mismatched types
--> src/main.rs:4:9
|
4 | Some(number) => number,
| ^^^^^^^^^^^^ expected integral variable, found enum `std::option::Option`
|
= note: expected type `{integer}`
found type `std::option::Option<_>`
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | None => 0,
| ^^^^ expected integral variable, found enum `std::option::Option`
|
= note: expected type `{integer}`
found type `std::option::Option<_>`
我尝试了类似 let try: i32 = 3;
的方法来确保 try
是一个整数值,但我仍然遇到同样的错误。
最佳答案
我想你想要这个:
fn main() {
let try = Some(3);
let x = match try {
Some(number) => number,
None => 0,
};
}
问题是您正在尝试将整数与 Some(...)
进行匹配和 None
, 这是 Option
秒。这真的没有意义......整数永远不可能是None
.
相反,我认为您想使用类型 Option<i32>
并将其转换为 i32
通过使用默认值。上面的代码应该可以做到这一点。请注意,如果这就是您要做的全部,那么这是一种更简单的方法:
let x = try.unwrap_or(0);
关于rust - 为什么在匹配整数时会出现错误 "expected integral variable, found Option"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44795582/