首页 > 其他 > 详细

rust 使用泛型来完成多态

时间:2020-03-24 22:57:54      阅读:183      评论:0      收藏: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}));
}

rust 使用泛型来完成多态

原文:https://www.cnblogs.com/liufu627/p/12562835.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!