8.5 Function Scope and Nested Functions

In Rust, functions can be nested, with each function introducing a new scope that defines where its identifiers are visible.

8.5.1 Scope of Top-Level Functions

Functions declared at the module level are accessible throughout that module. Their order in the file is irrelevant, as the compiler resolves them automatically.
To use a function outside its defining module, mark it with pub.

8.5.2 Nested Functions

Functions can also appear within other functions. These nested (inner) functions are only visible within the function that defines them:

fn main() {
    outer_function();
    // inner_function(); // Error! Not in scope
}

fn outer_function() {
    fn inner_function() {
        println!("This is the inner function.");
    }

    inner_function(); // Allowed here
}
  • inner_function can only be called from within outer_function.

Unlike closures, inner functions in Rust do not capture variables from the surrounding scope. If you need access to outer function variables, closures (discussed in Chapter 12) are the proper tool.