Search code examples
rusttypinginference

How do I specify one type argument and let Rust infer the rest?


I'm in the following situation:

fn some_fn<K, T, F, S>(func: F, other_func: S) -> Vec<i64>
where
    K: SomeType<T>,
    T: SomeOtherType,
    F: Fn() -> (),
    S: Fn() -> (),
{
    //...
}

For the above example, Rust can correctly infer types T, F, and S, but not K (as is expected).

Is there a way to only specify the type of K when calling some_fn without also specifying T, F, and S?

My current workaround is to change the signature to some_fn to fn some_fn<K, T, F, S>(cheat: Option<K>, func: F, other_func: S) and call the function like so:

let cheat: Option<SomethingThatImplements> = None;
let result = some_fn(cheat, func, other_func);

However, I find this to be very clunky. I haven't been able to find anything regarding this topic, is it even possible to specify only part of the type args?


Solution

  • Yes. Use _ for the arguments you want to infer:

    some_fn::<Foo, _, _, _>(...);