So I have this situation, where Rust cannot infer the generic type arguments for a function, that takes and optional Fn as a parameter.
When passing None
into it, it seems like the generic type arguments are obsolete, but Rust needs to know their values to compile and I don't know what to tell him. I tried foo::<(), ()>(calculation_result, None)
, but that doesn't work.
Does anyone know how I can call this foo
function when passing None
instead of a closure into it? Is there a dummy type I can specify or something?
The problem is to call a function with an unspecified parameter.
fn foo<F, R>(arg: bool, f: Option<F>) -> MyResult<R>
where F: Fn() -> R
{...}
foo(true, None); // <- R cannot be inferred
You have to manually specify the type. Keep in mind that Option gets optimised to the size of Box (not sizeof Box + 1) and does not allocate in the None case.
let empty: Option<Box<dyn Fn() -> ()>> = None;
foo(true, empty); // <- R is (), Option<Box<>>::None does not allocate