rust mopa

python;gutter:true;</p> <h1>[macro_use]</h1> <p>extern crate mopa;</p> <p>struct Bear { // This might be a pretty fat bear.</p> <pre><code>fatness: u16, </code></pre> <p>}</p> <p>impl Bear { fn eat(&mut self, person: Box) { self.fatness = (self.fatness as i16 + person.weight()) as u16; } }</p> <p>trait Person: mopa::Any { fn panic(&self); fn yell(&self) { println!("Argh!"); } fn sleep(&self); fn weight(&self) -> i16; }</p> <p>mopafy!(Person);</p> <p>struct Benny { // (Benny is not a superhero. He can't carry more than 256kg of food at once.) kilograms_of_food: u8, }</p> <p>impl Person for Benny { fn panic(&self) { self.yell() } fn sleep(&self) { /<em> ... </em>/ } fn weight(&self) -> i16 { // Who's trying to find out? I'm scared!</p> <pre><code> self.yell(); self.kilograms_of_food as i16 + 60 } </code></pre> <p>}</p> <p>struct Chris;</p> <p>impl Chris { // Normal people wouldn't be brave enough to hit a bear but Chris might.</p> <pre><code>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; } </code></pre> <p>}</p> <p>impl Person for Chris { fn panic(&self) { /<em> ... </em>/ } fn sleep(&self) { /<em> ... </em>/ } fn weight(&self) -> i16 { -5 /<em> antigravity device! cool! </em>/ } }</p> <p>fn simulate_simulation(person: Box, bear: &mut Bear) { if person.is::() { // None of the others do, but Benny knows this particular // bear by reputation and he's <em>really</em> going to be worried.</p> <pre><code> person.yell() } // If it happens to be Chris, he'll hit the bear. person.downcast_ref::().map(|chris| chris.hit(bear)); bear.eat(person); </code></pre> <p>}</p> <p>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); }

Original: https://www.cnblogs.com/pythonClub/p/16518377.html
Author: CrossPython
Title: rust mopa

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15790/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部