LoginSignup
8
11

More than 3 years have passed since last update.

Rustのファイル分割

Posted at

Rustのモジュールシステム(ファイル分割)

ディレクトリを作らない例(同階層のファイル)

workspace
├ src/
|  ├ main.rs
|  └ module_a.rs
├ Cargo.toml
└ Cargo.lock
module_a.rs
pub fn somefunction() {
  ...
}
main.rs
mod module_a; // module宣言

fn main() {
   module_a::somefunction();
}

または(呼び出しを短くしたいとき)

main.rs
use module_a::somefuncition();

fn main() {
   somefunction();
}

ディレクトリ分割(その1 同名スクリプト作成)

workspace
├ src/
|  ├ main.rs
|  ├ module_dir.rs //module_dirと同名+(.rs)
|  └ module_dir/
|      └ module_dir_a.rs
├ Cargo.toml
└ Cargo.lock
module_dir_a.rs
pub fn somefunction() {
  ...
}
module_dir.rs
pub mod module_dir_a;
main.rs
mod module_dir;

fn main() {
   module_dir_a::module_dir_a::somefunction(); //呼び出しが長い。
}

または(呼び出しを短くしたい場合)

main.rs
mod module_dir;
use module_dir::module_dir_a;

fn main() {
   module_dir_a::somefunction();
}

ディレクトリ分割(その2: mod.rs)

workspace
├ src/
|  ├ main.rs
|  └ module_dir/
|      ├ mod.rs
|      └ module_dir_a.rs
├ Cargo.toml
└ Cargo.lock
module_dir_a.rs
pub fn somefunction() {
  ...
}
mod.rs
pub mod module_dir_a;
main.rs
mod module_dir;
use module_dir;
fn main() {
  module_dir::module_dir_a::somefunction()
}

または(呼び出しを短くしたい場合)

main.rs
mod module_dir;
use module_dir::module_dir_a;

fn main() {
  module_dir::module_dir_a::somefunction()
}

まとめ

  • 同階層の場合、mod宣言で呼び出せる。
  • ディレクトリ分割の場合
    • ディレクトリ名と同じ名前のrsファイルをおき、そこでサブモジュールのmod宣言。
    • ディレクトリ配下にmod.rsをおきそこでサブモジュールのmod宣言
    • かつ、呼び出し側ではモジュールのmod宣言
    • useを使うと、サブモジュールをスコープ内に持ち込めるので、呼び出しが短くなる。

↓これが

main.rs
mod some_module;
fn main(){
  somemodule::submodule::somefunction()
}

↓こうなる。

main.rs
mod some_module;
use some_module::submodule;
fn main(){
  submodule::somefunction()
}

また、こう書くこともできる。

main.rs
mod some_module;
use some_module::submodule::*;
fn main(){
  somefunction()
}
8
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
11