知识卡片
默认值必须有业务意义
Default可减少创建结构体时重复填写可选字段,但只有字段确有合理默认值时才合适。出生日期等必填事实不能为方便构造而塞入任意日期;应让构造入口要求调用者提供。默认初始化解决语法重复,不会自动满足对象的业务不变量。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 7: Use builders for complex types · 查看原书依据
date_of_birth: time::Date, pub last_seen: Option<time::OffsetDateTime>, } error[E0277]: the trait bound `Date: Default` is not satisfied --> src/main.rs:48:9 | 41 | #[derive(Debug, Default)] | ------- in this derive macro expansion ... 48 | pub date_of_birth: time::Date, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Default` is not | implemented for `Date` | =
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Item 7: Use builders for complex types》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u038-ch01-049)。
- 结论依据:原文在“date_of_birth”附近的定义、例子或代码支撑本卡核心说明:Default可减少创建结构体时重复填写可选字段,但只有字段确有合理默认值时才合适。边界按已读前提解释;示例未执行。
- 原始内容:date_of_birth: time::Date, pub last_seen: Option<time::OffsetDateTime>, } error[E0277]: the trait bound `Date: Default` is not satisfied --> src/main.rs:48:9 | 41 | #[derive(Debug, Default)] | ------- in this derive macro expansion ... 48 | pub date_of_birth: time::Date, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Default` is not | implemented for `Date` | =