'Why doesn't Rust support overloading function or method? [closed]

Method overloading in java is a very helpful feature. Sometimes, we need define functions with the same name but with different set of arguments. I'm wondering why rust does not support this feature.



Solution 1:[1]

I would argue that in some way Rust does have function and method overloading.

Let's say you want to implement an abs() function that can either take an integer or a floating-point number. In C++, you could use

int abs(int x) { ... }
double abs(double x) { ... }

This will allow to call abs() with either an int or a double as an argument, and the compiler will choose the right implementation for you.

In Rust, you use traits instead. Traits can be implemented on foreign types including standarad types, so this is an adequate replacement:

trait Abs {
    fn abs(self) -> Self;
}

impl Abs for i32 {
    fn abs(self) -> Self { ... }
}

impl Abs for f32 {
    fn abs(self) -> Self { ... }
}

This will allow you to call x.abs(), where x is either an i32 or an f32, and the compiler will choose the right implementation for you.

You are not even limited to having the compiler base the decision on the method receiver alone. If you define a trait parametrized by a type, the compiler will choose the method implementation based on the type of additional parameters:

trait Trait<T> {
    fn foo(&self, x: T);
}

struct Bar;

impl Trait<i32> for Bar {
    fn foo(&self, _: i32) {
        println!("i32");
    }
}

impl Trait<u32> for Bar {
    fn foo(&self, _: u32) {
        println!("u32");
    }
}

fn main() {
    Bar.foo(1i32);  // prints "i32"
    Bar.foo(1u32);  // prints "u32"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sven Marnach