Volodymyr Prokopyuk
Volodymyr Prokopyuk

Reputation: 353

Pass function as argument to another function

I want to pass a function as argument to another function:

fn call(f: | i32, i32 | -> i32, x: i32) -> i32 {
  f(x, x)
}

fn main() {
  let res = call(| x, y | { x + y }, 4);
  println!("{}", res);
}

I get this error:

main.rs:1:12: 1:13 error: expected type, found `|`
main.rs:1 fn call(f: | i32, i32 | -> i32, x: i32) -> i32 {

What is the correct way to annotate function argument that is another function?

Upvotes: 2

Views: 1273

Answers (1)

fjh
fjh

Reputation: 13081

The following function signature is probably the simplest one that works:

fn call<F: FnOnce(i32, i32) -> i32>(f: F, x: i32) -> i32 {
    ...

There is also a section in the book that describes this.

Upvotes: 3

Related Questions