Struct visibility

Structs have an extra level of visibility with their fields. The visibility defaults to private, and can be overridden with the pub modifier. 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. // A public struct with a public field of generic type `T`
3. pub struct OpenBox<T> {
4. pub contents: T,
5. }

7. // A public struct with a private field of generic type `T`
8. #[allow(dead_code)]
9. pub struct ClosedBox<T> {
10. contents: T,
11. }

13. impl<T> ClosedBox<T> {
14. // A public constructor method
15. pub fn new(contents: T) -> ClosedBox<T> {
16. ClosedBox {
17. contents: contents,
18. }
19. }
20. }
21. }

23. fn main() {
24. // Public structs with public fields can be constructed as usual
25. let open_box = my::OpenBox { contents: "public information" };

27. // and their fields can be normally accessed.
28. println!("The open box contains: {}", open_box.contents);

30. // Public structs with private fields cannot be constructed using field names.
31. // Error! `ClosedBox` has private fields
32. //let closed_box = my::ClosedBox { contents: "classified information" };
33. // TODO ^ Try uncommenting this line

35. // However, structs with private fields can be created using
36. // public constructors
37. let _closed_box = my::ClosedBox::new("classified information");

39. // and the private fields of a public struct cannot be accessed.
40. // Error! The `contents` field is private
41. //println!("The closed box contains: {}", _closed_box.contents);
42. // TODO ^ Try uncommenting this line
43. }

See also:

generics and methods