0Pricing
Learn Rust Coding · Aula

Organização do Código com Módulos

Aprenda a utilizar o sistema de módulos do Rust para agrupar logicamente o código, gerir a privacidade e tornar os seus projetos escaláveis.

Organização do Código com Módulos é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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!

Perguntas Frequentes

A aula “Organização do Código com Módulos” é grátis?

Sim — o texto completo de “Organização do Código com Módulos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.

O que vou aprender em “Organização do Código com Módulos”?

Aprenda a utilizar o sistema de módulos do Rust para agrupar logicamente o código, gerir a privacidade e tornar os seus projetos escaláveis. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 3.

Quanto tempo leva a aula “Organização do Código com Módulos”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Organização do Código com Módulos
  2. Gestão de Dependências com Crates
  3. Tratamento Robusto de Erros com `Result`
← Voltar para Learn Rust Coding