モジュラーRust のファイル構成

RustRustBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、コード例のモジュールのファイル階層は以下のように表すことができます。「my」という名前のディレクトリがあり、その中に「inaccessible.rs」と「nested.rs」の2つのファイルが含まれています。また、「my.rs」という名前のファイルと「split.rs」という名前のファイルがあります。「split.rs」ファイルには、「my.rs」ファイルで定義された「my」モジュールが含まれており、「my.rs」ファイルには、それぞれ「inaccessible.rs」と「nested.rs」ファイルで定義された「inaccessible」と「nested」モジュールが含まれています。

注: 実験でファイル名が指定されていない場合、好きなファイル名を使用できます。たとえば、main.rs を使用して、rustc main.rs &&./main でコンパイルして実行することができます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/ProjectManagementandOrganizationGroup(["Project Management and Organization"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ProjectManagementandOrganizationGroup -.-> rust/module_system("Module System") subgraph Lab Skills rust/function_syntax -.-> lab-99336{{"モジュラーRust のファイル構成"}} rust/expressions_statements -.-> lab-99336{{"モジュラーRust のファイル構成"}} rust/method_syntax -.-> lab-99336{{"モジュラーRust のファイル構成"}} rust/module_system -.-> lab-99336{{"モジュラーRust のファイル構成"}} end

ファイル階層

モジュールはファイル/ディレクトリ階層にマッピングできます。ファイル内の可視性の例を分解してみましょう。

$ 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` ファイルを探し、それぞれのモジュールの下にここに挿入します
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()`

まとめ

おめでとうございます!あなたはファイル階層の実験を完了しました。あなたの技術を向上させるために、LabExでさらに多くの実験を行って練習してください。