Is it possible to overload bracket in rust?

I want to do so:

struct MyStruct{

}

fn main() {
    let s = MyStruct{};
    let re = s();//this is what I want
}

At present, I only know the square brackets can be overloaded.

On nightly, you can do it by implementing FnOnce, and optionally FnMut and Fn as well.

What you're looking for is the function call operator. It doesn't overload anything though. Unfortunately, at the moment the operator cannot be implemented in stable Rust.

Thanks for all of your replies. I found 2 related questions:
rust - How to create a sized closure or implement Fn/FnMut/FnOnce on a struct? - Stack Overflow
rust - How do I make a struct callable? - Stack Overflow
It seems to be not gonna be stable in near future.

Yeah. It's kinda hard for the compiler team to implement because it's not obvious how manual Fn* implementations would work with potential features like variadic functions or default/named arguments. Deciding to stabilise one path means that other paths will forever be out of reach, which is a difficult decision to make.

Most of the time people will introduce a named method which explains what the operation is doing. Another strategy is to use a closure which closes over any state you need access to so you still get function call syntax.

3 Likes

As for me, I would prefer variadic functions or default/named arguments, which I think are more useful.

But by the way, why could C++ combine all of these features, does C++ combine them in a messy way?

The usual way that languages deal with these problems is just ignoring the problems.

For example, C# has named arguments, but just didn't bother integrating that nicely with its Func types -- you just get arg1, arg2, arg3, etc if you try to call those with named arguments.

(Yes, you can make your own delegate types with different argument names in C#, but they're a different type, so that'd be kinda like making your own NotReallyAFn trait that has the names you want.)

2 Likes