Skip to content

Instantly share code, notes, and snippets.

@killerswan
Created June 11, 2014 17:26
Show Gist options
  • Save killerswan/09b7470505a9909ab390 to your computer and use it in GitHub Desktop.
Save killerswan/09b7470505a9909ab390 to your computer and use it in GitHub Desktop.
Overloading Rust functions on tuples by abusing traits :D
enum AaBbEnum {
Aa,
Bb,
}
trait AaBb {
fn get_type(&self) -> AaBbEnum;
fn get_aa(self) -> (int, f64) { fail!(); }
fn get_bb(self) -> (f64) { fail!(); }
}
impl AaBb for (int, f64) {
fn get_type(&self) -> AaBbEnum { Aa }
fn get_aa(self) -> (int, f64) { self }
}
impl AaBb for (f64) {
fn get_type(&self) -> AaBbEnum { Bb }
fn get_bb(self) -> (f64) { self }
}
#[cfg(not(test))]
fn overloaded<T: AaBb>(x: T) {
match x.get_type() {
Aa => println!("got Aa: {}", x.get_aa()),
Bb => println!("got Bb: {}", x.get_bb()),
}
}
fn overloaded_format<T: AaBb>(x: T) -> String {
match x.get_type() {
Aa => format!("got Aa: {}", x.get_aa()),
Bb => format!("got Bb: {}", x.get_bb()),
}
}
#[cfg(not(test))]
#[main]
fn main() {
overloaded((5i, 7.3243)); // prints: got Aa: (5, 7.3243)
overloaded((3.5)); // prints: got Bb: 3.5
}
#[test]
fn overloaded_with_same_return_works() {
// now with a shared return
let x: String = overloaded_format((5i, 7.3243));
let y: String = overloaded_format((3.5));
assert_eq!(x, "got Aa: (5, 7.3243)".to_string());
assert_eq!(y, "got Bb: 3.5".to_string());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment