0

I have a struct

struct A<F: Fn(i32)->i32>

How to define function which return it like

fn some_function() -> A<Fn(i32)->i32>

?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
doki
  • 85
  • 5
  • 2
    Does this answer your question? [How do I store a closure in a struct in Rust?](https://stackoverflow.com/questions/27831944/how-do-i-store-a-closure-in-a-struct-in-rust) – kotatsuyaki Jun 06 '22 at 06:11
  • You are aware that `Fn(i32) -> i32` is a trait, not a type, right? – jthulhu Jun 06 '22 at 06:21

1 Answers1

1

I think you need to use the fn type instead of the Fn trait:

struct A(fn(i32) -> i32);

fn some_function() -> A {
    let square = |x| x * x;
    A(square)
}

fn main() {
    let f = some_function();
    println!("{}", f.0(7));
}
49

You can of course also use the Fn trait, but then you need to use the impl keyword:

struct A<T: Fn(i32) -> i32>(T);

fn some_function() -> A<impl Fn(i32) -> i32> {
    let square = |x| x * x;
    A(square)
}

fn main() {
    let f = some_function();
    println!("{}", f.0(7));
}
49

impl here means "this is a type that I don't want to write here completely, but believe me, it implements Fn(i32) -> i32".

Finomnis
  • 18,094
  • 1
  • 20
  • 27