博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

rust 使用泛型来完成多态

Posted on 2020-03-24 22:54  liufu627  阅读(1201)  评论(0编辑  收藏  举报
trait Bird {
    fn fly(&self);
  }
  
  struct Duck{x:i32}
  struct Swan{x:i64}
  
  impl Bird for Duck {
    fn fly(&self) { println!("duck duck"); }
  }
  
  impl Bird for Swan {
    fn fly(&self) { println!("swan swan");}
  }

  fn test<T: Bird>(arg: T) {
    arg.fly();
  }

  fn test2(arg: Box<Bird>) {
    arg.fly();
  }

pub fn _main(){   
    test(Duck{x:10});
    test(Swan{x:10});

    test2( Box::new(Duck{x:10}));
    test2( Box::new(Swan{x:10}));
}