知识卡片
配置构造返回可预期错误
先验证输入数量,再用 Ok(config) 交付配置或用 Err 说明用户怎样修正输入。构造函数用 build 提示可能失败。将错误作为值返回可让调用方选择呈现方式。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- I/O 项目:构建命令行程序 Fixing the Error Handling · 查看原书依据
We can instead return a Result value that will contain a Config instance in the successful case and will describe the problem in the error case. We’re also going to change the function name from new to build because many programmers expect new functions to never fail. When Config::build is communicating to main, we can use the Result type to signal there was a problem.
参考来源
- 位置:《The Rust Programming Language(第2版)》第12章 I/O 项目:构建命令行程序(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c12.xhtml`,块 0115)
- 结论依据:原文解释 `build` 与 `Result` 怎样表达用户可纠正的输入错误。
- 原始内容:We can instead return a Result value that will contain a Config instance in the successful case and will describe the problem in the error case. We’re also going to change the function name from new to build because many programmers expect new functions to never fail. When Config::build is communicating to main, we can use the Result type to signal there was a problem.