【问题标题】:Group does not implement Data (FooMethod method has pointer receiver)Group 没有实现 Data(FooMethod 方法有指针接收器)
【发布时间】:2018-01-17 23:20:32
【问题描述】:

这是我的代码:

package main

import "fmt"

type Group struct {
}

func (g *Group) FooMethod() string {
    return "foo"
}

type Data interface {
    FooMethod() string
}

func NewJsonResponse(d Data) Data {
    return d
}

func main() {
    var g Group
    json := NewJsonResponse(g)
    fmt.Println("vim-go")
}

但没有按我的预期工作。

$ go build main.go
# command-line-arguments
./main.go:22: cannot use g (type Group) as type Data in argument to NewJsonResponse:
    Group does not implement Data (FooMethod method has pointer receiver)

【问题讨论】:

标签: go


【解决方案1】:

如果您想使用结构接收器,请在第 8 行的函数定义中从 Group 之前删除 *。为方便起见,它们确实以相反的方式工作(在 struct 上定义的工作在指针接收器上)。请参阅有效的解释。

https://golang.org/doc/effective_go.html#pointers_vs_values

修改版:

https://play.golang.org/p/ww6IYVPtIE

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 2019-11-23
    • 2016-02-29
    • 1970-01-01
    • 2019-11-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多