在 trait 的函数中,是否需要 &self 参数?

huangapple go评论61阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2023年5月11日 11:15:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定