学习 Rust 在声明 None 时出现编译错误

Learning rust getting compile error when declaring None

我目前正在阅读官方的 rust-lang 书籍(他们 website/documentation 上的那本),我正在通过复制代码和为所有内容写注释来做笔记。我目前在第 6 章,选项枚举类型。根据这本书和我在谷歌搜索时遇到的一些 Rustlings 代码,以下应该是可能的 based on the the official book

let none: Option<i32> = None;

我旁边还有评论表中的以下注释: If we use None rather than Some, we need to tell Rust what type of Option<T> we have, because the compiler can’t infer the type that the Some variant will hold by looking only at a None value. 我的意思是它满足要求,但我不断收到以下错误:

mismatched types
expected enum `main::Option<i32>`
   found enum `std::option::Option<_>`

我确实遇到了这个有效的方法:

let _equivalent_none = None::<i32>;

谁能解释为什么一个有效而另一个无效?官方书籍甚至没有提到第二种变体(不会引发错误)。最新版本和书中记载的有区别吗?

您似乎在程序中定义了自己的名为 Option 的枚举。因此,有两种称为 Option 的不同类型:您的 (main::Option) 和标准的 (std::option::Option)。变量 none 的类型为 main::Option,但 None 的类型为 std::option::Option.

显而易见的解决方案是删除您自己的枚举。但是,如果为了实验,您确实想创建一个名为 Option 的您自己的枚举实例,并将 None 的值分配给它,您需要限定 None:

let none: Option<i32> = Option::None;

问题在于,定义 enum Option { None, … } 会将新的 Option 引入作用域,默认情况下隐藏 std::prelude 导入的 std::option::Option。但是,enum Option { None, … } 不会将新的 None 引入作用域,因此 prelude 导入的 std::option::Option::None 仍然存在。

所以,你有两个选择:

  • 使用:let none: Option<i32> = Option::None;,明确指定要使用的none。
  • 在您的枚举下方添加一个 use crate::Option::*;,将您自己的 None 纳入范围。