Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass anonymous functions as parameters in Rust?

Tags:

I've been playing around with Rust the past week. I can't seem to figure out how to pass a function that is defined as a parameter when calling the method, and haven't come across any documentation that shows them being used in that fashion.

Is it possible to define a function in the parameter list when calling a function in Rust?

This is what I've tried so far...

fn main() {

    // This works
    thing_to_do(able_to_pass);

    // Does not work
    thing_to_do(fn() {
        println!("found fn in indent position");
    });

    // Not the same type
    thing_to_do(|| {
        println!("mismatched types: expected `fn()` but found `||`")
    });
}

fn thing_to_do(execute: fn()) {
    execute();
}

fn able_to_pass() {
    println!("Hey, I worked!");
}
like image 677
nathansizemore Avatar asked Aug 07 '14 12:08

nathansizemore


1 Answers

In Rust 1.0, the syntax for closure parameters is as follows:

fn main() {
    thing_to_do(able_to_pass);

    thing_to_do(|| {
        println!("works!");
    });
}

fn thing_to_do<F: FnOnce()>(func: F) {
    func();
}

fn able_to_pass() {
    println!("works!");
}

We define a generic type constrained to one of the closure traits: FnOnce, FnMut, or Fn.

Like elsewhere in Rust, you can use a where clause instead:

fn thing_to_do<F>(func: F) 
    where F: FnOnce(),
{
    func();
}

You may also want to take a trait object instead:

fn main() {
    thing_to_do(&able_to_pass);

    thing_to_do(&|| {
        println!("works!");
    });
}

fn thing_to_do(func: &Fn()) {
    func();
}

fn able_to_pass() {
    println!("works!");
}
like image 55
A.B. Avatar answered Sep 29 '22 05:09

A.B.