Is there a way to annotate a function that takes an optional closure in rust?

Viewed 455

I have a function that takes an optional closure and modifies a struct based on the return value.

For example:

fn main() {
  let mut s =  Struct::<usize> { inner: None };
  do_something(Some(|x:String|x.len()), &mut s);
  println!("{:?}",s);
  let mut s =  Struct::<usize> { inner: None };
  do_something(None, &mut s);

  println!("{:?}",s);
}

fn do_something<P, T: Fn(String) -> P>(fun: Option<T>, s: &mut Struct<P>) {
  *s = Struct {
      inner: fun.map(|fun| fun(String::from("abc")))
  };
}

#[derive(Debug)]
struct Struct<P> {
    inner: Option<P>
}

This should print:

Struct { inner: Some(3) }
Struct { inner: None }

But now it doesn't compile, since cannot infer type for type parameter T declared on the function do_something

Ok, let's try:

  let empty_function: Option<dyn Fn(String) -> usize> = None;
  do_something(empty_function, &mut s);

Also, doesn't work, since empty_function is unsized.

Is there a way annotate do_something so that this would work without Box?

1 Answers

You can specify the type of None with None::<T> and you can use function pointers (fn rather than dyn Fn) as basic sized pointers:

do_something(None::<fn(String) -> usize>, &mut s);
Related