知识卡片
用共享借用提供字段访问
隐藏字段可把调用者需要了解的内容限制在公开接口内,也让类型定义者决定何时更新状态。对于只承载交换数据的对象,直接公开字段有时更方便。需要对外只提供共享访问时,可为 name: T 生成 fn get_name(&self) -> &T { &self.name }。调用者可读取或传递借用,字段的所有权留在原结构体中。对具有内部可变性的字段仍需检查接口实际开放的能力。
书中 private! 读取具名字段的名字和类型,逐个生成访问器。因为这些信息来自结构体定义,只传类型名无法自动得到每个字段的签名。原样重发结构体并附上 getter 不会改变原字段可见性。教学代码还未将方法设为 pub,在同一模块内仍可直接读取原字段。把字段设为私有并给外部模块提供公开 getter 和构造入口,才能形成预期的接口。
相关卡片 [[扩展时重发原结构体]]、[[生成名字需要标识符]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 信息隐藏的目的
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 信息隐藏的目的 · 查看原书依据
Even in Rust, these practices have their place, at the very least from the perspective of easier reasoning about code. In fact, the language provides programmers with very good tooling for hiding information in structs, files, modules, etc. Information hiding is clearly dear to the creators’ hearts. Thus, our first example will focus on writing a macro that adds methods for allowing immutable access to fields via references. This is useful when structs contain fields that should be consulted or