英文:
Group does not implement Data (FooMethod method has pointer receiver)
问题
这是我的代码:
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)
英文:
This is my code:
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")
}
but does not work as I expect.
$ 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)
答案1
得分: 1
如果你想使用一个结构体接收器,就在第8行的函数定义中删除Group前面的*。作为一种便利,它们也可以反过来使用(在结构体上定义的函数可以在指针接收器上工作)。请参考《Effective Go》中的解释。
https://golang.org/doc/effective_go.html#pointers_vs_values
修改后的版本:
https://play.golang.org/p/ww6IYVPtIE
英文:
If you want to use a struct receiver, remove the * from before Group in the definition of your function on line 8. As a convenience they do work the other way round (defined on struct works on a pointer receiver). See effective go for an explanation.
https://golang.org/doc/effective_go.html#pointers_vs_values
Modified version:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论