WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 16 of 100

What is a module in Rust, and how do you define one?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, a module is a namespace that contains code definitions and declarations. It is used to group related code together, making it easy to organize and maintain large codebases.

A module can contain functions, structs, enums, constants, types, other modules, and more. In order to define a module, you need to use the ‘mod‘ keyword followed by a block of code.

Here’s an example of how to define a simple module:

    mod my_module {
        fn hello() {
            println!("Hello, world!");
        }
    }

In this example, we’ve defined a module called ‘my_module‘ that contains a single function named ‘hello‘. Note that the ‘fn‘ keyword is used to define a function inside a module, just like it is used to define a function outside of a module.

You can also nest modules inside other modules to create a hierarchy:

    mod my_module {
        mod nested_module {
            fn hello() {
                println!("Hello, nested world!");
            }
        }
    }

In this example, we’ve defined a module called ‘my_module‘ that contains another module called ‘nested_module‘. ‘nested_module‘ contains a single function named ‘hello‘.

To use the code inside a module, you need to use the ‘use‘ keyword to bring the module’s code into your current scope. Here’s an example:

    mod my_module {
        pub fn hello() {
            println!("Hello, world!");
        }
    }
    
    fn main() {
        my_module::hello();
    }

In this example, we’ve defined a module called ‘my_module‘ that contains a function named ‘hello‘. We’ve marked the function as ‘pub‘ so that it can be used outside of the module. In our ‘main‘ function, we’ve used the ‘use‘ keyword to bring the ‘my_module‘ module into our scope, so that we can call the ‘hello‘ function.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics