英文:
In Go, can both a type and a pointer to a type implement an interface?
问题
例如在下面的例子中:
type Food interface {
Eat() bool
}
type vegetable_s struct {
//一些数据
}
type Vegetable *vegetable_s
type Salt struct {
// 一些数据
}
func (p Vegetable) Eat() bool {
// 一些代码
}
func (p Salt) Eat() bool {
// 一些代码
}
Vegetable
和Salt
都满足Food
接口吗,即使一个是指针,另一个是直接的结构体?
英文:
For example in the following example:
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
}
Do Vegetable
and Salt
both satisfy Food
, even though one is a pointer and the other is directly a struct?
答案1
得分: 15
The answer is easy to get by compiling the code:
prog.go:19: invalid receiver type Vegetable (Vegetable is a pointer type)
The error is based on the specs requirement of:
> The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.
(Emphasizes mine)
The declaration:
type Vegetable *vegetable_s
declares a pointer type, ie. Vegetable
is not eligible as a method receiver.
英文:
The answer is easy to get by compiling the code:
prog.go:19: invalid receiver type Vegetable (Vegetable is a pointer type)
The error is based on the specs requirement of:
> The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.
(Emphasizes mine)
The declaration:
type Vegetable *vegetable_s
declares a pointer type, ie. Vegetable
is not eligible as a method receiver.
答案2
得分: 0
你可以这样做:
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{})
}
英文:
You could do the following:
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{})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论