モジュールによるコード整理
Rustのモジュールシステムを使ってコードを論理的にグループ化し、可視性を管理して、プロジェクトを拡張しやすくする方法を学びます。
「モジュールによるコード整理」はCoddyKit上の無料Learn Rust Codingレッスンです。 これはレッスン1/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはLearn Rust Coding学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Learn Rust Codingコースには全3レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Organize Your Code with Modules
As your Rust projects grow, keeping all your code in one file becomes messy. Rust's module system helps you organize code into logical units.
Modules are like folders for your code. They group related functions, structs, enums, and constants together, improving readability and maintainability.
Declaring Your First Module
You declare a module using the mod keyword, followed by the module's name. It's like creating a sub-namespace within your program.
Let's create a simple greetings module:
mod greetings {
// This is where greeting functions would go
}
fn main() {
println!("Hello from main!");
}Understanding Module Privacy
By default, everything inside a module is private. This means you can't access it from outside the module without explicitly making it public.
If you try to call a private function, Rust will give you a compile error. Try uncommenting the line below and running it:
mod greetings {
fn hello() {
println!("Hello from the greetings module!");
}
}
fn main() {
// Uncomment the line below and try to run!
// greetings::hello();
println!("Main function running.");
}Making Items Public with `pub`
To make an item (like a function, struct, or enum) visible from outside its module, you use the pub keyword.
pub fnmakes a function public.pub structmakes a struct public.pub modmakes a submodule public, allowing its contents to be accessed.
Privacy is a core part of Rust's safety and organization!
`pub` in Action
Now, let's make our hello function public using pub. This allows the main function to call it without a privacy error.
Run this code to see the greeting from our module:
mod greetings {
pub fn hello() {
println!("Hello from the greetings module!");
}
}
fn main() {
greetings::hello();
}Simplifying Paths with `use`
Typing out full paths like greetings::hello() can get repetitive. The use keyword lets you bring items into scope, making them easier to refer to.
It's similar to import in Python or using in C#. You can bring a specific item or an entire module into scope.
`use` in Action
Here's how you can use use to shorten the path to our hello function. Notice how we no longer need the greetings:: prefix.
This makes your code cleaner and easier to read.
mod greetings {
pub fn hello() {
println!("Hello, module user!");
}
}
use greetings::hello; // Bring `hello` into scope
fn main() {
hello(); // Now we can call it directly
}Nested Modules & Relative Paths
Modules can be nested! You can define modules inside other modules for even finer organization. For navigating these, Rust provides super and self.
superrefers to the parent module.selfrefers to the current module.
These are useful for relative paths within complex module hierarchies.
mod outer {
pub mod inner {
pub fn call_me() {
println!("Called from inner module!");
}
}
pub fn call_inner() {
// Accessing inner module from parent
inner::call_me();
}
}
fn main() {
outer::call_inner();
outer::inner::call_me();
}Modules and File Structure
For larger modules, you can put their code into separate files. Rust automatically looks for module definitions in specific locations:
- For
mod my_module;insrc/main.rs: Rust looks forsrc/my_module.rsorsrc/my_module/mod.rs. - This helps keep your main file clean and delegates content to appropriate files.
This lesson uses single files for simplicity, but remember this for bigger projects!
Module Access Check
Consider the following Rust code. Which lines will compile without a privacy error?
mod calculator {
fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
mod advanced {
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
}
}
fn main() {
// Line A
// calculator::add(5, 3);
// Line B
// calculator::subtract(10, 4);
// Line C
// calculator::advanced::multiply(2, 6);
// Line D
// calculator::advanced::add(1, 1);
}Modules: Organize & Control
Great job! You've learned how Rust's module system helps you structure your code:
- Use
modto declare modules and submodules. - Items are private by default; use
pubto make them accessible. usesimplifies long paths to items.- Modules can be spread across multiple files for large projects.
Modules are fundamental for managing complexity in Rust. Keep practicing!
よくある質問
「モジュールによるコード整理」レッスンは無料ですか?
はい。「モジュールによるコード整理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Learn Rust Codingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Learn Rust Codingコースには全3レッスンが含まれています。
「モジュールによるコード整理」で何を学びますか?
Rustのモジュールシステムを使ってコードを論理的にグループ化し、可視性を管理して、プロジェクトを拡張しやすくする方法を学びます。 ブラウザで直接実行するハンズオンコードでLearn Rust Codingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Learn Rust Codingを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのLearn Rust Codingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/3です。
「モジュールによるコード整理」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このLearn Rust Codingレッスンでコードを書いて実行できますか?
はい。すべてのLearn Rust Codingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- モジュールによるコード整理
- Crateによる依存関係管理
- `Result`による堅牢なエラー処理