Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Debug)]
- struct A {
- x: i32,
- }
- #[derive(Debug)]
- struct B {
- c: char,
- }
- trait Foo {
- fn foo(&mut self);
- }
- impl Foo for A {
- fn foo(&mut self) {
- self.x = 5;
- }
- }
- impl Foo for B {
- fn foo(&mut self) {
- self.c = 'F';
- }
- }
- fn do_same_thing_static_dispatch(f: &mut impl Foo) {
- println!("Doing something...");
- f.foo();
- println!("Doing something else...");
- }
- fn do_same_thing_dynamic_dispatch(f: &mut dyn Foo) {
- println!("Doing something...");
- f.foo();
- println!("Doing something else...");
- }
- fn main() {
- let mut a = A { x: 0 };
- let mut b = B { c: 'a' };
- do_same_thing_static_dispatch(&mut a);
- do_same_thing_static_dispatch(&mut b);
- do_same_thing_dynamic_dispatch(&mut a);
- do_same_thing_dynamic_dispatch(&mut b);
- dbg!(a, b);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement