Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a closure to a generic function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading