Group没有实现Data(FooMethod方法具有指针接收器)

huangapple go评论110阅读模式
英文:

Group does not implement Data (FooMethod method has pointer receiver)

问题

这是我的代码:

  1. package main
  2. import "fmt"
  3. type Group struct {
  4. }
  5. func (g *Group) FooMethod() string {
  6. return "foo"
  7. }
  8. type Data interface {
  9. FooMethod() string
  10. }
  11. func NewJsonResponse(d Data) Data {
  12. return d
  13. }
  14. func main() {
  15. var g Group
  16. json := NewJsonResponse(&g)
  17. fmt.Println("vim-go")
  18. }

但是它没有按照我期望的工作。

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

This is my code:

  1. package main
  2. import "fmt"
  3. type Group struct {
  4. }
  5. func (g *Group) FooMethod() string {
  6. return "foo"
  7. }
  8. type Data interface {
  9. FooMethod() string
  10. }
  11. func NewJsonResponse(d Data) Data {
  12. return d
  13. }
  14. func main() {
  15. var g Group
  16. json := NewJsonResponse(g)
  17. fmt.Println("vim-go")
  18. }

but does not work as I expect.

  1. $ go build main.go
  2. # command-line-arguments
  3. ./main.go:22: cannot use g (type Group) as type Data in argument to NewJsonResponse:
  4. 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:

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

huangapple
  • 本文由 发表于 2017年8月10日 06:04:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/45601338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定