0Pricing
Learn Rust Coding · Lección

Organización del código con módulos

Aprenda a utilizar el sistema de módulos de Rust para agrupar el código de forma lógica, gestionar la privacidad y hacer que sus proyectos sean escalables.

Organización del código con módulos es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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!

Preguntas frecuentes

¿La lección «Organización del código con módulos» es gratis?

Sí — el texto completo de «Organización del código con módulos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 3 lecciones en total.

¿Qué aprenderé en «Organización del código con módulos»?

Aprenda a utilizar el sistema de módulos de Rust para agrupar el código de forma lógica, gestionar la privacidad y hacer que sus proyectos sean escalables. Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 3.

¿Cuánto tiempo toma la lección «Organización del código con módulos»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Organización del código con módulos
  2. Gestión de dependencias con crates
  3. Gestión sólida de errores con `Result`
← Volver a Learn Rust Coding