Struct Visibility in Rust Programming


Structs in Rust contains an extra level of visibility. These can be modified by the developers as per his/her convenience.

In a normal scenario, the visibility of the struct in Rust is private and it can be made public by making use of the pub modifier.

It should be noted that this case of visibility only makes sense when we are trying to access the struct fields from outside the module, from where it is defined.

When we are hiding the fields of the struct, we are simply trying to encapsulate the data.

Example

Consider the example shown below −

mod my {
   // A public struct with a public field of generic type `T`
   pub struct OpenStruct {
      pub contents: T,
   }
   // A public struct with a private field of generic type `T`
   #[allow(dead_code)]
   pub struct ClosedStruct {
      contents: T,
   }
   impl ClosedStructx {
      // A public constructor method
      pub fn new(contents: T) -> ClosedStruct {
         ClosedStrut {
            contents: contents,
         }
      }
   }
}
fn main() {
   // Public structs with public fields can be constructed as usual
   let open_box = my::OpenStruct {
      contents: "public information"
   };
   // and their fields can be normally accessed.
   println!("The open box contains: {}", open_box.contents);
}

In the above code, we created two structs, both of them are public in nature, but one of the structs has its fields set as public, while the other structs field is private. Later in the main function, we are trying to construct the public fields of the public struct named OpenStruct, and then we print the fields.

Output

The open box contains: public information

Everything works fine. But, now if we try to access the struct named ClosedStruct, and its field just as we did for the OpenStruct, we will have this error.

Code

let closed_box = my::ClosedBox { contents: "classified information" };

We will get an error.

Output

error[E0451]: field `contents` of struct `ClosedBox` is private
--> src/main.rs:32:38
|
32| let closed_box = my::ClosedBox { contents: "classified
information" };
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private field

Though it should be noted that the structs with the private fields can be created using the public constructors, but still, we won’t be able to access the private fields.

let _closed_box = my::ClosedBox::new("classified information");

It will work fine.

Updated on: 03-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements