How can I make anything "callable"?

Is there a way to implement calling for any type similar to __call metamethod from Lua such that

struct MyCallable;
impl CallOp for MyCallable

will work.

PS. I am already aware that Fn* traits can be implemented however implementing them requires nightly only experimental features

Implementing Fn/FnMut/FnOnce would let you do this, but such impls are banned on stable Rust for now (due to unresolved questions like whether they should use hypothetical variadic generics). At least for Fn you can—but probably shouldn't—achieve something similar using the trick from this crate of dtolnay.

I would suggest just having an inherent method like this:

impl MyCallable {
    // or &self, or &mut self
    fn call(self, args: Args) -> Ret {

You're looking for the Fn, FnMut, or FnOnce traits (docs here). The semantics of these three traits are slightly different depending on how they borrow (or move) self.

I am aware of this but it requires nightly only apis

hackfn is pretty interesting thanks

I just remembered dtolnay has an in-depth explanation of the technique behind that crate here, which is good reading. (Again, I do not recommend applying this technique just to get slightly nicer custom callable types.)

I agree with you just added a call method to my type still does the job

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.