结构有可见性的一个额外的级别,它们的字段可以是公共或私有的(这是默认值)。这种可见只有当结构是从那里它被定义的模块外部访问重要的,它的目标是信息隐藏(封装)。
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
}