我是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
函数实现的。
在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."),
_ => (),
}
}
}