2013-07-27 103 views
4

例如,在下面的例子:在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 { 
    // some code 
} 

VegetableSalt既满足Food,即使一个是一个指针,另一个是直接一个结构?

回答

12

答案很容易通过compiling the code得到:

prog.go:19: invalid receiver type Vegetable (Vegetable is a pointer type) 

该错误是基于对specs要求:

接收器类型必须是形式为T或* T,其中T是一个类型名称。由T表示的类型称为接收器基类型; 它不能是指针或接口类型并且它必须在与方法相同的包中声明。

(强调矿)

声明:

type Vegetable *vegetable_s 

声明一个指针类型,即。 Vegetable不适合作为方法接收方。

+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{}) 
} 
+0

我想要它做的是,对于函数func foo(x Food){...},把它叫做'foo(vegetable_pointer)'而不是'foo(salt_value)'。 – Matt

+0

@Matt我在上面的答案中加了foo函数。如果对象作为参数传递给期望接口的方法,则这些对象将自动“包装”到目标接口中。 – metakeule

相关问题