Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ファイル階層

モジュールはファイル/ディレクトリ階層に対応付けることができます。 可視性の例をファイルに分割してみましょう。

$ tree .
.
├── my
│   ├── inaccessible.rs
│   └── nested.rs
├── my.rs
└── split.rs

split.rs では:

// この宣言は `my.rs` という名前のファイルを探し、
// その内容をこのスコープ配下の `my` という名前のモジュール内に挿入します
mod my;

fn function() {
    println!("called `function()`");
}

fn main() {
    my::function();

    function();

    my::indirect_access();

    my::nested::function();
}

my.rs では:

// 同様に、`mod inaccessible` と `mod nested` は
// `inaccessible.rs` ファイルと `nested.rs` ファイルを見つけ、
// それぞれのモジュール配下のここに挿入します
mod inaccessible;
pub mod nested;

pub fn function() {
    println!("called `my::function()`");
}

fn private_function() {
    println!("called `my::private_function()`");
}

pub fn indirect_access() {
    print!("called `my::indirect_access()`, that\n> ");

    private_function();
}

my/nested.rs では:

pub fn function() {
    println!("called `my::nested::function()`");
}

#[allow(dead_code)]
fn private_function() {
    println!("called `my::nested::private_function()`");
}

my/inaccessible.rs では:

#[allow(dead_code)]
pub fn public_function() {
    println!("called `my::inaccessible::public_function()`");
}

これまでと同じように動作することを確認しましょう。

$ rustc split.rs && ./split
called `my::function()`
called `function()`
called `my::indirect_access()`, that
> called `my::private_function()`
called `my::nested::function()`