0
votes

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
See Go, X does not implement Y (... method has a pointer receiver) for detailed explanation and possible solutions.icza

1 Answers

1
votes

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