首页 > 解决方案 > 学习 rust 在声明 None 时出现编译错误

问题描述

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

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>;

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

标签: rustenums

解决方案


看来您已经Option在程序中定义了自己的枚举。因此,有两种不同的类型称为Option:您的 ( main::Option) 和标准的 ( std::option::Option)。变量none有 type main::Option,但None属于 type std::option::Option

明显的解决方案是删除您自己的枚举。但是,如果出于实验目的,您确实想创建一个名为 的自己的枚举实例Option,并为其赋值,None则需要限定None

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

推荐阅读