Looking this example code
trait Animal {
fn make_sound(&self);
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) {
println!("Woof!");
}
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) {
println!("Meow!");
}
}
fn main() {
let dog = Dog;
let cat = Cat;
dog.make_sound();
cat.make_sound();
}
The function(method) make_sound()
is just print a string.
I check the content of this function, make_sound()
does not seems to invoke any information of Cat
struct.
So I tried to remove &self
parameter, but could not get the pass compiler.
Is &self necessary in the function of trait? Why?
Or where is my understanding wrong?
trait Animal {
fn make_sound();
}
struct Dog;
impl Animal for Dog {
fn make_sound() {
println!("Woof!");
}
}
struct Cat;
impl Animal for Cat {
fn make_sound() {
println!("Meow!");
}
}
fn main() {
let dog = Dog;
let cat = Cat;
dog.make_sound();
cat.make_sound();
}
No, a self
parameter is not required for trait functions. However, if there is no self
parameter, you can't use the obj.func()
syntax since there is no instance to be provided. You have to do Type::func()
:
trait Animal {
fn make_sound();
}
struct Dog;
impl Animal for Dog {
fn make_sound() {
println!("Woof!");
}
}
struct Cat;
impl Animal for Cat {
fn make_sound() {
println!("Meow!");
}
}
fn main() {
Dog::make_sound();
Cat::make_sound();
}
Woof!
Meow!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments