hiro99ma blog

Something technical

rust: Rustがんばろう 8日目

2025/02/21

はじめに

Rust を勉強することにした。
わざわざブログに書いているのは、あのとき私はこう思っていたんだ、と初心者だった自分を楽しみたいからかもしれない(初心者から脱せたとして)。

ファイル分け

前回書いたこちらを 2つのファイルに分けよう。

mod abc {
    fn hello(label: &str, value: &i32) {
        super::hello(label, value);
    }

    pub mod def {
        pub fn hello(label: &str, value: &i32) {
            super::hello(label, value);
        }
    }
}

fn hello(label: &str, value: &i32) {
    println!("{}: {}", label, value);
}

fn main() {
    let m = 10;
    abc::def::hello("m", &m);
}

分割1

// hello.rs
pub mod abc {
    fn hello(label: &str, value: &i32) {
        super::hello(label, value);
    }

    pub mod def {
        pub fn hello(label: &str, value: &i32) {
            super::hello(label, value);
        }
    }
}
// main.rs
mod hello;

use hello as abc;

fn hello(label: &str, value: &i32) {
    println!("{}: {}", label, value);
}

fn main() {
    let m = 10;
    abc::def::hello("m", &m);
}

これはダメだった。

最後の解決法が分からない。

failed to resolve: could not find `def` in `abc`
could not find `def` in `abc`

同じモジュールにいたときには呼び出せたので、そういうものというだけ?

あれ、そういえば hello.rs に直接 pub fn hello() を書いたら main.rs からどうやって呼び出すんだろう?
これは abc::hello() で呼び出せた。
ああああ、そういうことか。
hello.rs の中にある mod abc を参照しているつもりだったけど、実は hello.rs そのものがモジュールになっているのか。
7.5章のサンプルコードもそうなっているではないか。


分割2

// hello.rs
pub mod abc {
    fn hello(label: &str, value: &i32) {
        println!("{}: {}", label, value);
    }

    pub mod def {
        pub fn hello(label: &str, value: &i32) {
            super::hello(label, value);
        }
    }
}

pub fn hello(label: &str, value: &i32) {
    abc::def::hello(label, value);
}
// main.rs
mod hello;

fn main() {
    let m = 10;
    hello::hello("m", &m);
    hello::abc::def::hello("m", &m);
}

ちょっと形は変わったが、これは動く。
慣例に従うなら abc::defuse を使うべき、というところかな。

ディレクトリ分け

続けて、モジュールを別のディレクトリに置くやり方も書いてある。


分割3

pub fn hello(label: &str, value: &i32) {
    super::hello(label, value);
}
pub mod def;

fn hello(label: &str, value: &i32) {
    println!("{}: {}", label, value);
}
pub mod abc;

use abc::def;

pub fn hello(label: &str, value: &i32) {
    def::hello(label, value);
}
mod hello;

use hello::abc::def;

fn main() {
    let m = 10;
    hello::hello("m", &m);
    def::hello("m", &m);
}

mod ほげほげ { ... } と囲むのではなく、ほげほげ.rs に中身を書くという感じか。
そのモジュールA がさらにモジュールB を含んでいる場合は Aと同じ名前のディレクトリを作って、名前B の rsファイルを作る、と。

クレートルートを持っていなければどんなにしっかり実装しても単なるモジュールツリーだ。

コレクション

よくあるのが vector, list, map か。文字列はコレクションに入るのかよくわからないな。

おわりに

ようやく 8章まで眺め終わった。
ほんと「眺めた」程度だ。
全然実装できる気がせんなぁ。


 < Top page


コメント(Google Formへ飛びます)

GitHub

X/Twitter

Homepage