High Order Function with Type Parameter

That generic syntax means that the caller gets to chose the A and G types that it wants to call the function with, not that the body of the function can select whatever A it wants. It's saying "for every pair of types A which is Read and G which is Fn(A), there exists a function f that does this...". I don't know if there's any way to do what you want directly with the Fn trait. You'd really need to "lower" the A type parameter from the trait itself onto the trait's method. Something like this will work, for example:

trait Foo {
  fn call<A: Read>(&self, a: A);
}

fn f<G: Foo>(g: G, pred: bool) {
  if pred {
    g.call(File::open("foo").unwrap());
  } else {
    g.call(Cursor::new(b"foo"));
  }
}
1 Like