I have a function that takes a const generic value and a closure.
pub fn parse<const N: usize, F>(consumer: F)
where F: Fn(usize)
{
consumer(N * 2);
}
The function compiles fine. But I get a compile error when I try to call it.
parse::<10>(|n| {
println!("Closure called with: {}", n);
});
The error is:
this function takes 2 generic arguments but 1 generic argument was supplied
I used a type placeholder and it actually worked.
parse::<10, _>(|n| {
println!("Closure called with: {}", n);
});
Is there no other elegant way of doing this? If the const generics wasn’t there then Rust will have no problem inferring the closure type.
>Solution :
You can use a so-called "impl trait in argument positon" instead of a generic type parameter:
pub fn parse<const N: usize>(consumer: impl Fn(usize))
{
consumer(N * 2);
}
This is very similar to your original code, except that the type of consumer must always be implicit and cannot be explicitly specified with type parameters.