知识卡片
提前退出须匹配返回类型
? 需要当前函数能接收提前退出分支。在 Result 上使用时,上层返回值要能接收错误。在 Option 上使用时,None 直接返回,Some 交出内层值。两者不会由 ? 自动互换,要先调用 ok 丢弃错误信息,或用 ok_or 为缺值补出错误信息。
相关卡片 [[问号提前返回转换错误]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 错误处理 Where the ? Operator Can Be Used · 查看原书依据
Note that you can use the ? operator on a Result in a function that returns Result, and you can use the ? operator on an Option in a function that returns Option, but you can’t mix and match. The ?
参考来源
- 位置:《The Rust Programming Language(第2版)》第09章 错误处理(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c09.xhtml`,块 0125)
- 结论依据:原文直接指出问号不会隐式互换两种容器,并给出显式转换方法。
- 原始内容:Note that you can use the ? operator on a Result in a function that returns Result, and you can use the ? operator on an Option in a function that returns Option, but you can’t mix and match. The ?