0
0
Rustprogramming~5 mins

Module visibility in Rust

Choose your learning style9 modes available
Introduction

Module visibility controls which parts of your code can be seen and used by other parts. It helps keep your code organized and safe.

When you want to hide helper functions inside a module so others can't use them directly.
When you want to share some functions or data with other parts of your program.
When you want to organize your code into parts and control access between them.
When you want to prevent accidental changes to important parts of your code.
When you want to make your code easier to understand by showing only what is needed.
Syntax
Rust
mod my_module {
    pub fn public_function() {
        // code
    }

    fn private_function() {
        // code
    }
}

pub means the item is public and can be used outside the module.

Without pub, items are private and only usable inside the module.

Examples
cook is public and can be called from outside kitchen. clean is private and only usable inside kitchen.
Rust
mod kitchen {
    pub fn cook() {
        println!("Cooking food");
    }

    fn clean() {
        println!("Cleaning kitchen");
    }
}
The module tools and its function hammer are public, so they can be accessed from outside garage. The function open_door is private.
Rust
mod garage {
    pub mod tools {
        pub fn hammer() {
            println!("Using hammer");
        }
    }

    fn open_door() {
        println!("Opening garage door");
    }
}
Sample Program

This program shows a module house with a public submodule living_room. The function watch_tv is public and can be called from main. The other functions are private and cannot be called from outside their modules.

Rust
mod house {
    pub mod living_room {
        pub fn watch_tv() {
            println!("Watching TV in the living room");
        }

        fn clean_room() {
            println!("Cleaning the living room");
        }
    }

    fn lock_doors() {
        println!("Locking all doors");
    }
}

fn main() {
    house::living_room::watch_tv();
    // house::living_room::clean_room(); // This will cause an error because clean_room is private
    // house::lock_doors(); // This will cause an error because lock_doors is private
}
OutputSuccess
Important Notes

Use pub(crate) to make items visible only inside the current crate (project).

Modules can be nested, and visibility rules apply at each level.

Private items help keep your code safe by hiding details that should not be changed directly.

Summary

Module visibility controls what parts of code can be used outside their module.

pub makes items public; without it, items are private.

Use visibility to organize code and protect important parts.