Option 类型的类型转换

Kir*_*hou 3 casting type-conversion rust

我是 Python 的 Rust 新手。我相信这是一个基本问题,但我太新了,无法通过像Type Casting Option这样的关键字找到答案。

在Python中,为了让类型检查器知道返回类型不是Optional[int] + int,我们可以解决assert逻辑来强制类型检查器知道x永远不会在行None之后assert

from typing import Optional


def add_one(x: Optional[int] = None) -> int:
    if x is None:
        x = 0
    assert x is not None
    return x + 1


if __name__ == '__main__':
    add_one(0)    # 1
    add_one()     # 1
    add_one(999)  # 1000
Run Code Online (Sandbox Code Playgroud)

在 Rust 中,假设接口相同,如何实现相同的事情?x即,如何让编译器知道不再是类型Option

fn add_one(mut x: Option<i32>) -> i32 {
    if x == None {
        x = Some(0);
    }
    return x + 1;
}

fn main() {
    add_one(Some(0));
    add_one(None);
    add_one(Some(999));
}
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

error[E0369]: binary operation `+` cannot be applied to type `std::option::Option<i32>`
 --> tmp.rs:5:14
  |
5 |     return x + 1;
  |            - ^ - {integer}
  |            |
  |            std::option::Option<i32>
  |
  = note: an implementation of `std::ops::Add` might be missing for `std::option::Option<i32>`
Run Code Online (Sandbox Code Playgroud)

请注意,我尝试过添加另一个类型为 i32 ( ) 的变量let y: i32 = x;,但它对以下消息不起作用。

error[E0308]: mismatched types
 --> tmp.rs:5:22
  |
5 |     let y: i32 = x;
  |                  ^ expected i32, found enum `std::option::Option`
  |
  = note: expected type `i32`
             found type `std::option::Option<i32>`
Run Code Online (Sandbox Code Playgroud)

Fre*_*ios 8

使用unwrap_or

fn add_one(x: Option<i32>) -> i32 {
    x.unwrap_or(0) + 1
}

fn main() {
    assert_eq!(1, add_one(Some(0)));
    assert_eq!(1, add_one(None));
    assert_eq!(1000, add_one(Some(999)));
}
Run Code Online (Sandbox Code Playgroud)