3 ms·
But rust doesn't even has function overloading
by The_rationalist 6y ago
But rust doesn't even has function overloading
- deleted 6y ago[deleted]
- steveklabnik 6y agoThey’re two very different features.
- wwright 6y agoIt does, in a sense; you could say it has a “structured” way to overload functions that significantly simplifies resolution and predictability. People don’t really call it overloading, but it has many similarities.
- gpderetta 6y agotype classes, rust traits and overloading are all a form of ad-hoc polymorphism, hence the similarity.
- MaulingMonkey 6y agoRust "doesn't" have function overloading, but it effectively does: fn main() { foo((42)); foo((12.0, 13.0)); } pub fn foo(args: impl FooArgs) { args.exec() } pub trait FooArgs { fn exec(self); } impl FooArgs for u32 { fn exec(self) { println!("A number: {}", self) } } impl FooArgs for (f32, f32) { fn exec(self) { println!("{} x {} = {}", self.0, self.1, self.0 * self.1) } } https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b726f7f6e21c250aba62f9fe61e6d5a0 https://play.rust-lang.org/?version=stable&mode=debug&editio... A number: 42 12 x 13 = 156 Usually you won't abuse tuples quite like this, but it's an option. The same pattern of using traits - without the tuples - is more common [1]. Or if you need variadic functions, typically you'd resort to a macro instead. [1]: https://medium.com/@jreem/advanced-rust-using-traits-for-argument-overloading-c6a6c8ba2e17 https://medium.com/@jreem/advanced-rust-using-traits-for-arg...