Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait A: std::fmt::Debug {
- fn a(&self) {
- println!("Hello I'm {:?}", self);
- }
- }
- #[derive(Debug)]
- struct B;
- impl B {
- fn new() -> Self {
- println!("[Associated function] Creating B");
- B
- }
- fn observe_c(&self, _: &C) {
- println!("[Method] got C!");
- }
- }
- impl A for B {}
- #[derive(Debug)]
- struct C;
- impl C {
- fn new() -> Self {
- println!("[Associated function] Creating C");
- C
- }
- fn observe_b(&self, _: &B) {
- println!("[Method] got B!");
- }
- }
- impl A for C {}
- fn static_dispatch<T: A>(value: &T) {
- print!("[Static dispatch] ");
- value.a();
- }
- fn dynamic_dispatch(value: &dyn A) {
- print!("[Dynamic dispatch] ");
- value.a();
- }
- fn main() {
- let b = B::new();
- let c = C::new();
- b.observe_c(&c);
- c.observe_b(&b);
- static_dispatch(&b);
- static_dispatch(&c);
- dynamic_dispatch(&b);
- dynamic_dispatch(&c);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement