Created
September 30, 2016 16:03
-
-
Save subnomo/08623f36a6f210409998bf2daf20c6f9 to your computer and use it in GitHub Desktop.
How to overload functions in Rust using traits. Updated from source - https://goo.gl/StPQ1B
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Foo { | |
value: u32 | |
} | |
trait HasUIntValue { | |
fn as_uint(self) -> u32; | |
} | |
impl Foo { | |
fn add<T: HasUIntValue>(&mut self, value: T) { | |
self.value += value.as_uint(); | |
} | |
} | |
impl HasUIntValue for i32 { | |
fn as_uint(self) -> u32 { | |
return self as u32; | |
} | |
} | |
impl HasUIntValue for f64 { | |
fn as_uint(self) -> u32 { | |
return self as u32; | |
} | |
} | |
#[test] | |
fn test_add_with_int() { | |
let mut x = Foo { value: 10 }; | |
x.add(10i32); | |
assert!(x.value == 20); | |
} | |
#[test] | |
fn test_add_with_float() { | |
let mut x = Foo { value: 10 }; | |
x.add(10.0f64); | |
assert!(x.value == 20); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment