How to do it...

  1. Create a file named sample_struct.rs in the project workspace
  2. Write the code header with the details of the code:
        //-- #########################
//-- Task: To create a sample nested_mod module
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 4 March 17
//-- #########################
  1. Create a sample module named sample_struct, in which you can declare a public struct named WhiteBox:
        // Sample module which has struct item
mod sample_struct {
// A public struct with a public field of generic type `T`
pub struct WhiteBox<T> {
pub information: T,
}
  1. Declare a public struct named BlackBox with a private generic type T:
        // A public struct with a private field of generic type `T`
#[allow(dead_code)]
pub struct BlackBox<T> {
information: T,
}
  1. Create a public constructor named const_new using the impl keyword, which takes the generic T type as input:
        impl<T> BlackBox<T> {
// A public constructor method
pub fn const_new(information: T) -> BlackBox<T> {
BlackBox {
information: information,
}
}
}
}
  1. Declare the main function by calling the struct items of thesample_struct module, which is the whitebox struct item:
        // Execution starts here
fn main() {

// Public structs with public fields can be constructed as
usual
let white_box = sample_struct::WhiteBox { information:
"public
information n" };

// and their fields can be normally accessed.
println!("The white box contains: {} ",
white_box.information);
// Public structs with private fields cannot be constructed
using field names.
// Error! `BlackBox` has private fields
//let black_box = sample_struct::BlackBox { information:
"classified information" };
// TODO ^ Try uncommenting this line
// However, structs with private fields can be created using

// public constructors
let _black_box = sample_struct::BlackBox::const_new("classified
information ");

// and the private fields of a public struct cannot be
accessed.
// Error! The `information` field is private
//println!("The black box contains: {}",
_black_box.information);
// TODO ^ Try uncommenting this line
}

Upon the correct setup of the preceding code, you should get the following output when you compile and run the program:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.206.25