» Quick Introduction to Rust » 1. Basics » 1.10 Modules

Modules

Rust provides a powerful module system that can be used to hierarchically split code in logical units (modules).

Visibility

By default, the items in a module have private visibility, but this can be overridden with the pub modifier.

mod a_mod {
    fn private_func() {
        println!("a_mod::private_func");
    }

    // Use the `pub` modifier to override default visibility.
    pub fn func() {
        println!("a_mod::func");
    }
}

fn main() {
    // OK
    a_mod::func();
    // error[E0603]: function `private_func` is private
    a_mod::private_func();
}

Struct Visibility

Structs have an extra level of visibility with their fields. The visibility defaults to private, and can be overridden with the pub modifier.

mod a_mod {
    // A public struct with a public field
    pub struct S1<T> {
        pub content: T,
    }

    // A public struct with a private field
    pub struct S2<T> {
        content: T,
    }
}

fn main() {
    // OK
    let s1 = a_mod::S1 {content: "public"};
    println!("content: {}", s1.content);

    // error[E0451]: field `content` of struct `S2` is private
    let s2 = a_mod::S2 {content: "private"};
    // error[E0616]: field `content` of struct `S2` is private
    println!("content: {}", s2.content);
}

use

The use declaration can be used to bind a full path to a new name, for easier access.

use crate::deeply::nested::{
    a_function,
    ATraitType
};

fn main() {
    a_function();
}

You can use the as keyword to bind imports to a different name:

use deeply::nested::a_function as better_name_function;

super and self

The super and self keywords can be used in the path to remove ambiguity when accessing items.

fn function() {
    println!("called `function()`");
}

mod a_mod {
    fn function() {
        println!("called `a_mod::function()`");
    }

    pub fn call() {
        self::function(); // called `a_mod::function()
        function(); // called `a_mod::function()

        super::function(); // called `function()`
    }
}

fn main() {
    a_mod::call();
}

Code Challenge

Try to modify the code provided in the editor to finish the calculator.

Loading...
> code result goes here
Prev
Next