rust 如何为包含另一个方法的结构继承方法

qfe3c7zg  于 2022-12-29  发布在  其他
关注(0)|答案(1)|浏览(153)

我是C++背景的新手。我写了下面的代码来理解代码的可重用性,这是继承背后的唯一目的。

/* in animal.rs */
//declare Animal here
pub struct Animal;

// implement Animal here
impl Animal
{
    pub fn breathe(&self)
    {
        println!("All animals breathe!");
    }
}

// declare Dog here
pub struct Dog 
{
    pub parent: Animal
}

// implement Dog here
impl Dog
{
    pub fn bark(&self)
    {
        println!("Dogs bark!");
    }
    pub fn breathe(&self)
    {
        self.parent.breathe();
    }
}

/* in main.rs */
mod animal;

fn main() 
{
    let d = animal::Dog {parent : animal::Animal};
    d.bark();
    d.breathe();
}

如果我不在Dog中实现breathe函数,编译器就找不到它。在C中,子函数继承其父函数。有人能解释一下吗?
补充问题:有人能展示一些示例代码吗?动态/后期绑定是如何在rust中工作的。在C
中,它是通过virtual函数实现的。

mspsb9vt

mspsb9vt1#

Rust中没有结构继承,但是你可以像下面的例子一样使用trait来定义一个共享行为,你可以看到dyn AnimalTrait关键字,它在Rust中用于动态调度。

trait AnimalTrait {
    fn is_canine(&self) -> String {
        return String::from("canine");
    }
}

pub struct Dog;
impl AnimalTrait for Dog {}

pub struct Cat;
impl AnimalTrait for Cat {}

pub struct Mouse;
impl AnimalTrait for Mouse {
    fn is_canine(&self) -> String {
        return String::from("not canine");
    }
}

fn main() {
    let (d, c, m) = (Dog {}, Cat {}, Mouse {});

    let all_animals: Vec<Box<dyn AnimalTrait>> = vec![Box::new(d), Box::new(c), Box::new(m)];

    for e in all_animals {
        match e.is_canine().as_str() {
            "canine" => println!("I can tear apart well."),
            "not canine" => println!("I will have hard time tearing apart."),
            _ => (),
        }
    }
}

相关问题