rust - 学习 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>;
谁能解释为什么一个有效而另一个无效?官方书籍甚至没有提到第二个变体(不会引发错误)。最新版本与书中记录的不同吗?
解决方案
看来您已经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;
推荐阅读
- java - 在 Java 中向 Rest Web 服务发送 JSON Post 请求
- angular - 如何从 html 文件中调用服务方法。?
- python - 线性回归怀疑。手动验证值
- javascript - 使用 jquery 捕获所有单击事件,无论元素单击事件是否具有 stopPropagation
- animation - ThreeJS GLB IK 动画导出
- c# - 如何在 EF / EF Core 的第二个表上实现具有某些条件的左连接?
- javascript - 如何使用 Reactjs 代码开发 windows 桌面应用程序
- coq - 等号coq的解释传递性
- azure - 我们可以使用 Azure CLI 将文件上传到 Azure Data Lake Storage Gen2
- javascript - 查找匹配给定字符串中的两个子子字符串的正则表达式