英文:
Is &self parameter necessary in the function of trait?
问题
以下是您提供的代码的翻译:
在这个例子中,make_sound()
函数(方法)只是打印一个字符串。
我检查了这个函数的内容,make_sound()
似乎没有调用任何关于 Cat
结构的信息。
所以我尝试删除 &self
参数,但无法通过编译器。
在 trait 的函数中,&self
参数是否是必需的?为什么?
或者我的理解哪里出错了?
编辑:添加不能通过编译器的代码
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();
}
英文:
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?
Edit: Add code which could not get the pass compiler
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();
}
答案1
得分: 3
No, self
参数对于特质函数并不是必需的。但是,如果没有 self
参数,您就无法使用 obj.func()
语法,因为没有实例可供提供。您必须使用 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!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论