Skip to content

Instantly share code, notes, and snippets.

@aalexandrov
Last active February 15, 2022 22:09
Show Gist options
  • Save aalexandrov/1be0c0dad72acbd1570b95cbbf832a6a to your computer and use it in GitHub Desktop.
Save aalexandrov/1be0c0dad72acbd1570b95cbbf832a6a to your computer and use it in GitHub Desktop.
Method overloading in Rust
#[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