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. }
  6. // A public struct with a private field of generic type `T`
  7. #[allow(dead_code)]
  8. pub struct ClosedBox<T> {
  9. contents: T,
  10. }
  11. impl<T> ClosedBox<T> {
  12. // A public constructor method
  13. pub fn new(contents: T) -> ClosedBox<T> {
  14. ClosedBox {
  15. contents: contents,
  16. }
  17. }
  18. }
  19. }
  20. fn main() {
  21. // Public structs with public fields can be constructed as usual
  22. let open_box = my::OpenBox { contents: "public information" };
  23. // and their fields can be normally accessed.
  24. println!("The open box contains: {}", open_box.contents);
  25. // Public structs with private fields cannot be constructed using field names.
  26. // Error! `ClosedBox` has private fields
  27. //let closed_box = my::ClosedBox { contents: "classified information" };
  28. // TODO ^ Try uncommenting this line
  29. // However, structs with private fields can be created using
  30. // public constructors
  31. let _closed_box = my::ClosedBox::new("classified information");
  32. // and the private fields of a public struct cannot be accessed.
  33. // Error! The `contents` field is private
  34. //println!("The closed box contains: {}", _closed_box.contents);
  35. // TODO ^ Try uncommenting this line
  36. }

See also:

generics and methods