9.1 Visibility
기본적으로, 모듈의 아이템들은 private의 가시성을 갖고, 이는 pub 수정자로 재정의 될 수 있다. 오직 public 아이템이 외부의 모듈의 영역에서도 접근될 수 있다.
// `my` 모듈
mod my {
// 모듈의 아이템은 기본적으로 private의 가시성을 갖는다.
fn private_function() {
println!("called `my::private_function()`");
}
// `pub` 지시어를 통해 기본 가시성을 재정의 한다.
pub fn function() {
println!("called `my::function()`");
}
// 동일 모듈의 아이템은 다른 아이템이 private여도 접근할 수 있다.
pub fn indirect_access() {
print!("called `my::indirect_access()`, that\n> ");
private_function();
}
// 모듈은 중첩 될 수 있다.
pub mod nested {
pub fn function() {
println!("called `my::nested::function()`");
}
#[allow(dead_code)]
fn private_function() {
println!("called `my::nested::private_function()`");
}
}
// 중첩 모듈도 동일한 가시성 규칙을 적용받는다.
mod private_nested {
#[allow(dead_code)]
pub fn function() {
println!("called `my::private_nested::function()`");
}
}
}
fn function() {
println!("called `function()`");
}
fn main() {
// 모듈은 동일 이름을 가진 아이템 간에 모호성을 허용한다.
function();
my::function();
// 중첩 모듈을 포함하여 public 아이템은 상위 모듈에서 접근된다.
my::indirect_access();
my::nested::function();
// nested 모듈이 pub이라도 모듈의 Private 아이템은
// 직접적으로 접근 할 수 없다.
// 에러! `private_function`은 private.
//my::private_function();
// TODO ^ 해당 라인의 주석을 제거해보세요.
// 에러! `private_function`은 private
//my::nested::private_function();
// TODO ^ 해당 라인의 주석을 제거해보세요.
// 에러! `private_nested`는 private 모듈
//my::private_nested::function();
// TODO ^ 해당 라인의 주석을 제거해보세요.
}