知识卡片
枚举方法共用入口
在 impl Message 上可以定义由所有变体共享的方法。方法以 self 或其引用获得本次接收的整个消息,然后可以依据变体区分动作。空变体、具名字段变体与元组式变体都归入同一个 Message 类型,调用方可以只面对一个接口。
相关卡片 [[枚举统一互斥变体]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 枚举与模式匹配 Defining an Enum · 查看原书依据
impl Message { fn call(&self) { ❶ // method body would be defined here } } ❷ let m = Message::Write(String::from("hello")); m.call();
参考来源
- 位置:《The Rust Programming Language(第2版)》第06章 枚举与模式匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c06.xhtml`,块 0043)
- 结论依据:枚举 impl 和 Write 变体实例的调用展示了枚举也有方法。
- 原始内容:impl Message { fn call(&self) { ❶ // method body would be defined here } } ❷ let m = Message::Write(String::from("hello")); m.call();