ファイルの階層構造

モジュールはファイル・ディレクトリの階層構造と対応関係にあります。以下の様なファイルで可視性の例を詳しく見ていきましょう。

$ 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`によって、`nested.rs`、`inaccessible.rs` // の内容をこの中で使用することができるようになります。 // 訳注:`pub`をつけないかぎり、この中でしか使用できません。 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()`