rust中dyn关键字的用法

以下代码是chatGPT给出的示例代码,智能AI果然NB

// Define a trait for an animal
trait Animal {
    fn make_sound(&self) -> &'static str;
}

// Define two structs that implement the Animal trait
struct Dog;
struct Cat;

impl Animal for Dog {
    fn make_sound(&self) -> &'static str {
        "Woof!"
    }
}

impl Animal for Cat {
    fn make_sound(&self) -> &'static str {
        "Meow!"
    }
}

// Define a function that returns a trait object on the heap
fn random_animal(random_number: f64) -> Box<dyn Animal> {
    if random_number < 0.5 {
        Box::new(Dog)
    } else {
        Box::new(Cat)
    }
}

fn main() {
    let random_number = 0.234;
    let animal = random_animal(random_number);
    println!("You got a {}!", animal.make_sound());
}
```
posted @   天使不设防  阅读(98)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示