Private versus public fields

By default, all fields within a struct are private to the module it is created in. This has its uses; for example, if you want to protect a value within the struct, you can make it only accessible via a read/write function, as shown in the following example:

// readwrite.rs 
pub struct RWData 
{ 
    pub X: i32, 
    Y: i32 
} 
 
static mut rwdata: RWData = RWData {X: 0, Y: 0}; 
 
pub fn store_y(val: i32) 
{ 
    unsafe { rwdata.Y = val; }
} 
 
pub fn new_y() -> i32 
{ 
    unsafe { rwdata.Y * 6 }
} 
 
// main.rs 
mod readwrite; 
use readwrite::*; 
 
fn main() { 
    
 
        store_y(6); 
        println!("Y is now {}", new_y()); 
     
} 
The code for this section is in the 07/readwrite folder, present in the supporting code bundle provided for this book.

When we build and run this, we will get the following output:

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

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