Skip to content

Instantly share code, notes, and snippets.

@ktrysmt
Created March 25, 2020 12:01
Show Gist options
  • Save ktrysmt/111bdf75a8aceb425f62202a1172ec38 to your computer and use it in GitHub Desktop.
Save ktrysmt/111bdf75a8aceb425f62202a1172ec38 to your computer and use it in GitHub Desktop.
implement common methods with global function or polymorphism
struct Example {
number: i32,
}
impl Example {
fn boo() {
println!("boo! Example::boo() was called!");
}
fn answer(&mut self) {
self.number += 42;
}
fn get_number(&self) -> i32 {
self.number
}
}
trait Thingy {
fn do_thingy(&self) {
println!("doing a thing! also, number is {}!", self.number);
}
}
impl Thingy for Example {}
// main
fn main() {
let e = Example { number: 99 };
e.do_thingy();
}
struct Super {}
trait SuperTrait<T: Staff> {
fn common_method(common: T);
}
impl<T: Staff> SuperTrait<T> for Super {
fn common_method(state: T) {
println!("get number via super: {}.", state.get_number());
}
}
struct X {
width: i32,
}
struct Y {
height: i32,
}
trait Staff {
fn get_number(&self) -> i32;
}
impl Staff for X {
fn get_number(&self) -> i32 {
self.width
}
}
impl Staff for Y {
fn get_number(&self) -> i32 {
self.height
}
}
fn main() {
let x = X { width: 1 };
let y = Y { height: 2 };
Super::common_method(x);
Super::common_method(y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment