9.2 Struct visibility

구조체는 그들 필드에 추가 가시성을 갖는다. 가시성은 기본적으로 private이고, pub 수정자로 재정의 될 수 있다. 이 가시성은 오직 정의된 외부 모듈에서 접근될 때만 의미가 있고, 정보를 숨기는 것이 목적이다(캡슐화). Structs have an extra level of visibility with their fields. The visibility defaults to private, and can be overridden with the pub modifier. This visibility only matters when a struct is accessed from outside the module where it is defined, and has the goal of hiding information (encapsulation).

mod my {
// `T` public public
pub struct WhiteBox<T> {
pub contents: T,
}
// `T` private public
#[allow(dead_code)]
pub struct BlackBox<T> {
contents: T,
}
impl<T> BlackBox<T> {
// A public constructor method
pub fn new(contents: T) -> BlackBox<T> {
BlackBox {
contents: contents,
}
}
}
}
fn main() {
// public public .
let white_box = my::WhiteBox { contents: "public information" };
// .
println!("The white box contains: {}", white_box.contents);
// private public .
// ! `BlackBox` private .
//let black_box = my::BlackBox { contents: "classified information" };
// TODO ^ .
// , private public .
let _black_box = my::BlackBox::new("classified information");
// public private .
// ! `contents` private.
//println!("The black box contains: {}", _black_box.contents);
// TODO ^ .
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

See also:

generics and methods

results matching ""

    No results matching ""