8.8 Nested Functions and Scope

8.8.1 Nested Functions

In Rust, you can define functions inside other functions. These are called nested functions or inner functions.

fn main() {
    fn inner_function() {
        println!("This is an inner function.");
    }
    inner_function();
    println!("This is the main function.");
}
  • Scope: The inner function inner_function is only visible within the main function.

8.8.2 Function Visibility

  • Top-Level Functions: Visible throughout the module.
  • Nested Functions: Only visible within the enclosing function.
  • You cannot call a nested function from outside its scope.

Example:

fn main() {
    outer_function();
    // inner_function(); // Error: not found in this scope
}
fn outer_function() {
    fn inner_function() {
        println!("Inner function");
    }
    inner_function(); // This works
}