rust actually has function overloading

159 points ali_compute_unit 71 comments

while rust doesnt support function overloading natively because of its consequences and dificulties.

using the powerful type system of rust, you can emulate it with minimal syntax at call site.

using generics, type inference, tuples and trait overloading.

trait OverLoad<Ret> {
    fn call(self) -> Ret;
}

fn example<Ret>(args: impl OverLoad<Ret>) -> Ret {
    OverLoad::call(args)
}

impl OverLoad<i32> for (u64, f64, &str) {
    fn call(self) -> i32 {
        let (a, b, c) = self;
        println!("{c}");
        (a + b as u64) as i32
    }
}
impl<'a> OverLoad<&'a str> for (&'a str, usize) {
    fn call(self) -> &'a str {
        let (str, size) = self;
        &str[0..size * 2]
    }
}
impl<T: Into<u64>> OverLoad<u64> for (u64, T) {
    fn call(self) -> u64 {
        let (a, b) = self;
        a + b.into()
    }
}
impl<T: Into<u64>> OverLoad<String> for (u64, T) {
    fn call(self) -> String {
        let (code, repeat) = self;
        let code = char::from_u32(code as _).unwrap().to_string();
        return code.repeat(repeat.into() as usize);
    }
}

fn main() {
    println!("{}", example((1u64, 3f64, "hello")));
    println!("{}", example(("hello world", 5)));
    println!("{}", example::<u64>((2u64, 3u64)));
    let str: String = example((b'a' as u64, 10u8));
    println!("{str}")
}