Pointers 在Go中,类型和指向类型的指针都可以实现接口吗?
例如,在以下示例中:Pointers 在Go中,类型和指向类型的指针都可以实现接口吗?,pointers,interface,struct,go,Pointers,Interface,Struct,Go,例如,在以下示例中: type Food interface { Eat() bool } type vegetable_s struct { //some data } type Vegetable *vegetable_s type Salt struct { // some data } func (p Vegetable) Eat() bool { // some code } func (p Salt) Eat() bool { //
type Food interface {
Eat() bool
}
type vegetable_s struct {
//some data
}
type Vegetable *vegetable_s
type Salt struct {
// some data
}
func (p Vegetable) Eat() bool {
// some code
}
func (p Salt) Eat() bool {
// some code
}
蔬菜和盐是否都满足食品,即使一个是指针,另一个直接是结构?答案很容易得到: 误差基于以下要求: 接收方类型必须为T或*T格式,其中T是类型名称。用T表示的类型称为接收器基类型它不能是指针或接口类型,并且必须在与方法相同的包中声明 (我的) 宣言:
type Vegetable *vegetable_s
声明指针类型,即
不符合方法接收器的条件。您可以执行以下操作:
package main
type Food interface {
Eat() bool
}
type vegetable_s struct {}
type Vegetable vegetable_s
type Salt struct {}
func (p *Vegetable) Eat() bool {return false}
func (p Salt) Eat() bool {return false}
func foo(food Food) {
food.Eat()
}
func main() {
var f Food
f = &Vegetable{}
f.Eat()
foo(&Vegetable{})
foo(Salt{})
}
我想让它做的是,对于函数func foo(x Food){…}
,将其称为foo(蔬菜指针)
,但是foo(盐值)
@Matt我在上面的答案中添加了foo函数。如果对象作为参数传递给期望接口的方法,则对象会自动“包装”到目标接口中。有人知道为什么要这样设计吗?
package main
type Food interface {
Eat() bool
}
type vegetable_s struct {}
type Vegetable vegetable_s
type Salt struct {}
func (p *Vegetable) Eat() bool {return false}
func (p Salt) Eat() bool {return false}
func foo(food Food) {
food.Eat()
}
func main() {
var f Food
f = &Vegetable{}
f.Eat()
foo(&Vegetable{})
foo(Salt{})
}