HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

A local function in Rust

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionlocalrust

Problem

In there any way in Rust to create a local function which can be called more than once. The way I'd do that in Python is:
def method1():
def inner_method1():
print("Hello")

inner_method1()
inner_method1()

Solution

Yes, you can define functions inside functions:

fn method1() {
    fn inner_method1() {
        println!("Hello");
    }

    inner_method1();
    inner_method1();
}


However, inner functions don't have access to the outer scope. They're just normal functions that are not accessible from outside the function. You could, however, pass the variables to the function as arguments. To define a function with a particular signature that can still access variables from the outer scope, you must use closures.

Code Snippets

fn method1() {
    fn inner_method1() {
        println!("Hello");
    }

    inner_method1();
    inner_method1();
}

Context

Stack Overflow Q#26685666, score: 133

Revisions (0)

No revisions yet.