How to add extension method for closures

Hey all,

I would like to add extension methods for closures. What I would like to achieve is the following:

    #[test]
    fn test_method() {
        (|| panic!("error")).do_something();
    }

So what I want is to add the do_something method for closures. As far as I know, traits can be used to extend existing types. In other contexts I have successfully extended existing types such as String, but this time I could not make it work.

Here is what I tried:

trait Behaviour {
    fn do_something();
}
impl<T> Behaviour for T where T: FnOnce() {
    fn do_something(){
        println!("some test")

    }
}

But I got the following compilation error when I try to run above specified test:

no method named `do_something` found for closure `[closure@src\doer.rs:23:9: 23:29]` in the current scope

this is an associated function, not a method

Could you please help me and point it out where my problem lies and how to add extension method for closures?

Thanks in advance!

It works.

Just make sure do_something is a method (takes self, &self or &mut self) and not an associated function.

2 Likes

damn, I was close, thanks a lot!