知识卡片
类型状态限制可用操作
类型状态模式把对象当前所处阶段编码进类型参数,高层操作只在对应的实现块中提供。红绿灯示例的 TrafficLight<Green> 有 turn_red,返回 TrafficLight<Red>,后者只有 turn_green。Light 是无方法的标记特征,PhantomData<T> 让类型持有编译期标记而无需存储一份状态值。于是从红色再调用 turn_red 会因方法不存在而在编译阶段被拒绝。书中演示约束链上的方法可用性。实际需要线性转移的对象还要选择合适的所有权接口。
相关卡片 [[构建器用类型强制填字段]]。
结构图:
classDiagram
class Light {
<<trait>>
}
class Green
class Red
class TrafficLight~T~ {
marker PhantomData~T~
}
class GreenLight["TrafficLight<Green>"] {
+turn_red(&self) TrafficLight~Red~
}
class RedLight["TrafficLight<Red>"] {
+turn_green(&self) TrafficLight~Green~
}
Light <|.. Green : 实现标记
Light <|.. Red : 实现标记
TrafficLight ..> Light : 泛型约束
GreenLight ..> RedLight : 转红后返回
RedLight ..> GreenLight : 转绿后返回
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Builder with attributes 通过类型排除非法转移 · 查看原书依据
We can use the type state pattern to do that, encoding the state of our system in a type parameter. A simple example might help illustrate the idea. We have a traffic light that is either green or red.
参考来源
- 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p111)
- 结论依据:8.5.1 从红绿灯切换推导状态标记作为泛型参数,清单 8.20 用不同 impl 暴露不同方法。
- 原始内容:We can use the type state pattern to do that, encoding the state of our system in a type parameter. A simple example might help illustrate the idea. We have a traffic light that is either green or red.