rust 使用泛型来完成多态


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}));
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM