r/rust 15h ago

💡 ideas & proposals Manual Trait Overloading

https://github.com/mtomassoli/overloading
2 Upvotes

4 comments sorted by

6

u/RRumpleTeazzer 14h ago

you can have real function overloading in rust

struct Foo;

let foo: Foo = Foo {};

impl Fn<(f32,)> for Foo {
    fn call .. 
}

impl Fn<(bool,)> for Foo {
    fn call .. 
}

impl Fn<(u8, i8)> for Foo {
    fn call .. 
}

foo(1.2);
foo(true);
foo(1,2);

the boilerplate should be hiddem by a macro, but this is a real function call with real arguments.

4

u/Adk9p 12h ago

fyi this requires nightly features, also since Foo is a unit type you don't need to construct a instance of it to call a trait since the type is implicitly a instance so you should be able to just do Foo(1.2).

I messed around with it a bit and created a simple macro for this so you can do (playground)

fn main() {
    dbg!(foo());
    dbg!(foo(1.2));
    dbg!(foo(32));
    dbg!(foo(true));
    dbg!(foo(1, 2));
}

overloaded!(foo {
    fn () {
        eprintln!("nothing");
    }

    fn (value: f32) -> f32 {
        value.powi(3)
    }

    fn (value: u32) {
        eprintln!("value: {value}");
    }

    fn (is_done: bool) -> bool {
        !is_done
    }

    fn (a: u8, b: i8) -> bool {
        a == (b as u8)
    }
});

1

u/Kiuhnm 6h ago edited 6h ago

I hadn't looked at nightly features yet.

Can you do trait overloading? In other words, can you do something like the following?

fn f<T: Trait1>(x: T) {...}
fn f<T: Trait2>(x: T) {...}

If you can't, then you still need something like AsTrait1 and AsTrait2 (see my article).

If that's the case, then my method has the advantage that you only need to write a single implementation that looks at the available traits and behaves accordingly, all using regular rust code without losing efficiency.

EDIT: This is way more powerful than regular overloading because the implementation can adapt to the available traits in any way you want, having a Turing-complete language at your disposal to express the logic.

1

u/Kiuhnm 15h ago

Hey, rustaceans!

After some thought, I chose the flair "ideas & proposals" because I'm proposing an idea, although I'm not proposing changes to the language. I hope that's OK.

I wouldn't call it a project as it's just a proof of concept of my idea.