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

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

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:

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:

确定