0Pricing
Learn Rust Coding · Lektion

Code mit Modulen organisieren

Lernen Sie, das Modulsystem von Rust zu verwenden, um Code logisch zu gruppieren, Sichtbarkeit zu verwalten und Ihre Projekte skalierbar zu machen.

Code mit Modulen organisieren ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 1 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 3 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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 fn makes a function public.
  • pub struct makes a struct public.
  • pub mod makes 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.

  • super refers to the parent module.
  • self refers 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; in src/main.rs: Rust looks for src/my_module.rs or src/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 mod to declare modules and submodules.
  • Items are private by default; use pub to make them accessible.
  • use simplifies long paths to items.
  • Modules can be spread across multiple files for large projects.

Modules are fundamental for managing complexity in Rust. Keep practicing!

Häufig gestellte Fragen

Ist die Lektion „Code mit Modulen organisieren“ kostenlos?

Ja — der vollständige Text von „Code mit Modulen organisieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 3 Lektionen.

Was lerne ich in „Code mit Modulen organisieren“?

Lernen Sie, das Modulsystem von Rust zu verwenden, um Code logisch zu gruppieren, Sichtbarkeit zu verwalten und Ihre Projekte skalierbar zu machen. Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Learn Rust Coding zu starten?

Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 3.

Wie lange dauert die Lektion „Code mit Modulen organisieren“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?

Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Code mit Modulen organisieren
  2. Abhängigkeiten mit Crates verwalten
  3. Robuste Fehlerbehandlung mit `Result`
← Zurück zu Learn Rust Coding