5 ms·
Rust "doesn't" have function overloading, but it effectively does: fn main() { foo((42)); foo((12.0, 13.0)); } pub fn foo(args: impl FooArgs
by MaulingMonkey 6y ago
Rust "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...