标签:mut self bear person rust Chris mopa fn
#[macro_use] extern crate mopa; struct Bear { // This might be a pretty fat bear. fatness: u16, } impl Bear { fn eat(&mut self, person: Box<dyn Person>) { self.fatness = (self.fatness as i16 + person.weight()) as u16; } } trait Person: mopa::Any { fn panic(&self); fn yell(&self) { println!("Argh!"); } fn sleep(&self); fn weight(&self) -> i16; } mopafy!(Person); struct Benny { // (Benny is not a superhero. He can’t carry more than 256kg of food at once.) kilograms_of_food: u8, } impl Person for Benny { fn panic(&self) { self.yell() } fn sleep(&self) { /* ... */ } fn weight(&self) -> i16 { // Who’s trying to find out? I’m scared! self.yell(); self.kilograms_of_food as i16 + 60 } } struct Chris; impl Chris { // Normal people wouldn’t be brave enough to hit a bear but Chris might. fn hit(&self, bear: &mut Bear) { println!("Chris hits the bear! How brave! (Or maybe stupid?)"); // Meh, boundary conditions, what use are they in examples? // Chris clearly hits quite hard. Poor bear. bear.fatness -= 1; } } impl Person for Chris { fn panic(&self) { /* ... */ } fn sleep(&self) { /* ... */ } fn weight(&self) -> i16 { -5 /* antigravity device! cool! */ } } fn simulate_simulation(person: Box<dyn Person>, bear: &mut Bear) { if person.is::<Benny>() { // None of the others do, but Benny knows this particular // bear by reputation and he’s *really* going to be worried. person.yell() } // If it happens to be Chris, he’ll hit the bear. person.downcast_ref::<Chris>().map(|chris| chris.hit(bear)); bear.eat(person); } fn main() { let mut bear = Bear { fatness: 10 }; simulate_simulation(Box::new(Benny { kilograms_of_food: 5 }), &mut bear); simulate_simulation(Box::new(Chris), &mut bear); }
标签:mut,self,bear,person,rust,Chris,mopa,fn 来源: https://www.cnblogs.com/pythonClub/p/16518377.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。