D. Ataro
D. Ataro

Reputation: 1821

How would one return a function from a function in Rust?

What I currently have and have tried:

fn locate_func() -> fn() -> bool {
    func_exit()
}

The above piece of code shows what I am trying to accomplish. I would like to return func_exit in the form of what I assume would be a pointer, to whatever variable binding might decide it needs that specific code, as well as once I have retrieved the function I would like to run it. But I am certain that I can figure out the running part on my own.

&func_exit()

I have tried, but as you would most certainly know that simply evaluates the function and then returns a pointer pointing to the boolean on the stack.

*&func_exit()
&*func_exit() // or

I believe I saw something similar in the Rust book at some point, but I have tried both of those combinations for this case, as well as tried doing the same thing with parenthesis in all the different ways, but that still evaluates the function first, then points to the evaluated boolean.

Upvotes: 5

Views: 5484

Answers (1)

Shepmaster
Shepmaster

Reputation: 430310

The parenthesis mean "call the function with these arguments". Don't do that:

fn func_exit() -> bool {
    println!("hi");
    true
}

fn locate_func() -> fn() -> bool {
    func_exit
}

fn main() {
    let f = locate_func();
    f();
}

Related but distinct: Returning a closure from a function.

Upvotes: 11

Related Questions