结构体的可见性

结构体对字段的可见性有额外的规定(Structs have an extra level of visibility with their fields)。其可见性默认为私有,也可以加上 pub 修饰语来改变默认属性。只有当从定义在外部的模块访问一个结构体时,这可见性才显得重要,并具有隐藏信息的目的(封装,encapsulatoin)(原文:This visibility only matters when a struct is accessed from outside the module where it is defined, and has the goal of hiding information (encapsulation))。

1. mod my {
2. // 一个公有的结构体,带有一个公有的泛型类型 `T` 的字段
3. pub struct WhiteBox<T> {
4. pub contents: T,
5. }

7. // 一个公开的结构体,带有一个私有的泛型类型 `T` 的字段
8. #[allow(dead_code)]
9. pub struct BlackBox<T> {
10. contents: T,
11. }

13. impl<T> BlackBox<T> {
14. // 一个公有的构造器方法
15. pub fn new(contents: T) -> BlackBox<T> {
16. BlackBox {
17. contents: contents,
18. }
19. }
20. }
21. }

23. fn main() {
24. // 带有公有字段的公有的结构体,可以像平常一样构造
25. let white_box = my::WhiteBox { contents: "public information" };

27. // 并且它们的字段可以正常访问到。
28. println!("The white box contains: {}", white_box.contents);

30. // 带有私有字段的公有结构体不能使用字段名来构造。
31. // 报错!`BlackBox` 含有私有字段。
32. //let black_box = my::BlackBox { contents: "classified information" };
33. // 试一试 ^ 将此行注释去掉

36. // 不过带有私有字段的结构体可以使用公有的构造器来创建。
37. let _black_box = my::BlackBox::new("classified information");

39. // 并且一个结构体中的私有字段不能访问到。
40. // 报错!`content` 字段是私有的。
41. //println!("The black box contains: {}", _black_box.contents);
42. // 试一试 ^ 将此行注释去掉

44. }

参见:

泛型 and 方法