Last active
February 15, 2022 22:09
-
-
Save aalexandrov/1be0c0dad72acbd1570b95cbbf832a6a to your computer and use it in GitHub Desktop.
Method overloading in Rust
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
#[derive(Debug)] | |
struct Container { | |
x: i32, | |
y: usize, | |
} | |
trait Contains<T> { | |
fn get(&self) -> &T; | |
fn set(&mut self, value: T); | |
} | |
impl Contains<i32> for Container { | |
fn get(&self) -> &i32 { | |
&self.x | |
} | |
fn set(&mut self, value: i32) { | |
self.x = value; | |
} | |
} | |
impl Contains<usize> for Container { | |
fn get(&self) -> &usize { | |
&self.y | |
} | |
fn set(&mut self, value: usize) { | |
self.y = value; | |
} | |
} | |
fn main() { | |
let mut c = Container { x: 0, y: 0 }; | |
c.set(37 as i32); | |
c.set(42 as usize); | |
println!( | |
"Container {{ x: {}, y: {} }}", | |
c.get() as &i32, | |
c.get() as &usize | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment