Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 11, 2024 18:54
Show Gist options
  • Save max-itzpapalotl/dd2593cff2918185ea8dc98cb4579fc0 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/dd2593cff2918185ea8dc98cb4579fc0 to your computer and use it in GitHub Desktop.
11. Modules

11. Modules

Defining Modules and visibility

mod a {
    fn g() {
        println!("g");
    }
    pub fn f() {
        println!("f");
        g();
    }
    pub mod b {
        pub fn h() {
            println!("h");
        }
    }
}

fn main() {
    a::f();
    a::b::h();
}

Subdirectories

src/main.rs:

mod a;

fn main() {
    a::f();
    a::b::h();
}

src/a.rs:

fn g() {
    println!("g");
}
pub fn f() {
    println!("f");
    g();
}
pub mod b;

src/a/b.rs:

pub fn h() {
    println!("h");
}

use

The use statements binds a local name to a name from a different module:

src/main.rs:

mod a;

use a::f;
use a::b::h as hhh;

fn main() {
    f();
    hhh();
}

It is possible to import multiple names:

src/main.rs:

mod a;

use a::{f, b::h};

fn main() {
    f();
    h();
}

Visibility

Code in a module (including the top level) can see all public declarations, its own private declarations, and private declarations up in the hierarchy, but nothing else.

So this is possible (going back to all modules in the same file):

mod a {
    fn g() {
        println!("g");
    }
    pub fn f() {
        println!("f");
        g();
        b::i();
    }
    pub mod b {
        pub fn h() {
            println!("h");
            crate::a::g();   // up in the hierarchy!
        }
        pub fn i() {         // this pub is needed for b::i() above!
            println!("i");
        }
    }
}

fn main() {
    a::f();
    a::b::h();
}

super, self and crate

self refers to the current module, super refers to the module one up in the hierarchy. crate refers to the top level of the currently compiled crate.

src/main.rs:

mod a {
    fn g() {
        println!("g");
    }
    pub fn f() {
        println!("f");
        self::g();
        b::i();
    }
    pub mod b {
        pub fn h() {
            println!("h");
            super::g();   // up in the hierarchy!
        }
        pub fn i() {
            println!("i");
        }
    }
}

fn main() {
    a::f();
    a::b::h();
}

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment