Home > OS >  getting "the value of the associated type `Output` (from trait `FnOnce`) must be specified"
getting "the value of the associated type `Output` (from trait `FnOnce`) must be specified"

Time:01-20

I have a function that takes 3 arguments namely a, b and a function that takes them and return the value that function produed.

fn from_func<T>(a: i32, b: i32, func: Fn) -> i32 {
    func(a, b)
}

but when im calling it :

fn main() {
    let my_func = |a: i32, b: i32| a   b;
    println!("{:?}", from_func(15, 20, my_func));
}

I'm getting

error[E0191]: the value of the associated type `Output` (from trait `FnOnce`) must be specified
 --> src\main.rs:5:34
  |
5 | fn from_func<T>(a:i32,b:i32,func:Fn)->i32{
  |                                  ^^ help: specify the associated type: `Fn<Output = Type>`

I tried using where keyword and it worked

fn from_func<T>(a: i32, b: i32, func: T) -> i32
where
    T: Fn(i32, i32) -> i32
{
    func(a,b)
}

but is there any other way of doing this?

CodePudding user response:

but is there any other way of doing this?

You must constrain the type variable to provide the arguments and return type of the function. You can do that with a where clause, which is probably best because it's on another line so makes the signature less cluttered.

But you could do this:

fn from_func<F: Fn(i32, i32) -> i32>(a: i32, b: i32, func: F) -> i32 {
    func(a, b)
}

Or, avoid a named type variable by using an impl trait, like this:

fn from_func(a: i32, b: i32, func: impl Fn(i32, i32) -> i32) -> i32 {
    func(a, b)
}
  • Related