Why Rust doesn't have function overloading?

Not necessarily. I have only done four of your functions, but you get the idea:

struct Foo(String);
impl Foo { fn new(x: impl NewFoo) -> Self { x.new() } }

trait NewFoo { fn new(self) -> Foo; }

impl NewFoo for &str { fn new(self) -> Foo { println!("&str"); Foo(self.to_string()) } }
impl NewFoo for String { fn new(self) -> Foo { println!("String"); Foo(self) } }
impl NewFoo for &String { fn new(self) -> Foo { println!("&String"); Foo(self.clone()) } }
impl NewFoo for Box<String> { fn new(self) -> Foo { println!("Box<String>"); Foo(Box::<String>::into_inner(self)) } }

Why? Overloading in Rust differs from overloading in C++ the same way generics in Rust differ from templates in C++: while C++ defers ambiguity resolution till call time (called instantiation time for templates) Rust insists on resolution of conflicts at define time.

That's why I could't implement what you write fully: some of your definitions conflict.

This makes overloads in Rust much safer. The only issue is the fact that you can't pass many arguments to your new function (but can pass a tuple!).

Oh, absolutely. I like overloads in Rust much better than in C++. The only issue is lack of support for multiple arguments.

Of course if you add some random crazy feature which would behave in random crazy way you may get crazy results.

There are no implicit overloads in Rust and that's fine. Rust does support explicit overloads and that's pretty cool, really.

If you would do what compiler does with Fn/FnMut/FnOnce today by adding couple of additional braces when you need multiple arguments you can see how hypothetical extension would behave, too. On nightly you can use overloadable and see how the whole thing works.

I missed it till I read about how it's supposed to work. Now I only miss the ability to pass multiple arguments.

Apparently this is kept unimplemented to make it possible to implement variadic generics is some bright future. Not sure how that coercion may hurt… but maybe there are some dark deep reasons, IDK.

2 Likes