LoginSignup
0
1

More than 1 year has passed since last update.

Rustでファイルに切り出したコードをモジュールとして呼び出す

Posted at

Rustでファイルに切り出したコードをモジュールとして呼び出す方法

まとめ

mod ファイル名  // 例 mod sample

fn main() {
    ファイル名::関数名;  // 例 sample::hello();
}

詳細

例として、標準入力された値を文字列として返すモジュール

ファイル

src/
  ┠ main.rs
  ┗ read_buffer.rs

コード

src/read_buffer.rs
use std::io;

pub fn return_as_string() -> String {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("Failed to read line.");
    return buffer.trim().to_string();
}
src/main.rs
mod read_buffer;

fn main() {
    println!("{}", read_buffer::return_as_string())
}

※ src配下のファイル名を mod XXX として呼び出すことができる

実行

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/read-buffer`
Hello!  # ← Input
Hello!  # ← Output
0
1
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
0
1