【问题标题】:In Go, can both a type and a pointer to a type implement an interface?在 Go 中,类型和指向类型的指针都可以实现接口吗?
【发布时间】:2013-07-27 20:25:35
【问题描述】:

例如在下面的例子中:

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,即使一个是指针而另一个直接是结构?

【问题讨论】:

    标签: pointers interface struct go


    【解决方案1】:

    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】:

    您可以执行以下操作:

    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(vegetable_pointer),但称为foo(salt_value)
    • @Matt 我在上面的答案中添加了 foo 函数。如果将对象作为参数传递给期望接口的方法,则对象会自动“包装”在目标接口中。
    猜你喜欢
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2013-11-11
    • 2015-04-06
    • 2021-01-26
    • 2014-02-16
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多