Rust可視性

Rust可視性

結構有可見性的一個額外的級別,它們的字段可以是公共或私有的(這是默認值)。這種可見只有當結構是從那裏它被定義的模塊外部訪問重要的,它的目標是信息隱藏(封裝)。

mod my {
// A public struct with public fields
pub struct WhiteBox

{
pub contents: T,
}

// A public struct with private fields
#\[allow(dead\_code)\]
pub struct BlackBox

{ contents: T, } impl

 BlackBox

  { // A public constructor pub fn new(contents: T) -> BlackBox

   { BlackBox { contents: contents, } } } } fn main() { // Public structs with public fields can be constructed as usual let white\_box = my::WhiteBox { contents: "public information" }; // and their fields can be normally accessed println!("The white box contains: {}", white\_box.contents); // but public structs with private fields can't be constructed // Error! \`BlackBox\` has private fields //let black\_box = my::BlackBox { contents: "classified information" }; // TODO ^ Try uncommenting this line // However, structs with private fields can still be created using // constructors let \_black\_box = my::BlackBox::new("classified information"); // The private fields of a struct can't be accessed // Error! The \`contents\` field is private //println!("The black box contains: {}", \_black\_box.contents); // TODO ^ Try uncommenting this line }