-2

I am trying to type assert in Go but error says struct doesn't implement interface method but I have clearly implemented method declared in interface.

This is the code I am trying to execute

package interfaces

import "fmt"

type Event interface {
    Accept()
}

type Like struct {
}

// Like implement Accept method from Event interface
func (l *Like) Accept() {
  fmt.Println("like accept")
}

func TypeAssertionExample() {
 var l *Like = &Like{}
 var e Event = l
 _, f := e.(Like) // error even after Like implemented Accept method 
 fmt.Println(f)
}
Mithun Kumar
  • 595
  • 1
  • 9
  • 18

2 Answers2

2

Note that in addition to what Hymns for Disco suggested, we can modify your example (I've changed it to package main and func main for use on the Go Playground) so that instead of:

func (l *Like) Accept) {
    // code
}

we have:

func (l Like) Accept() {
    // code
}

and the code will then compile. But since e holds an instance of *Like, not one of Like, the test:

_, f := e.(Like)
fmt.Println(f)

prints false now. See the complete example here.

The question of when and whether to use pointer receivers is quite a basic one, and covered fairly well, though not explicitly, in the Go Tour. The FAQ has the same information in a more compact form, with some explicit details in a second section. See also Value receiver vs. pointer receiver.

torek
  • 448,244
  • 59
  • 642
  • 775
1

Pointer types and non-pointer types aren't the same. You need to do this:

_, f := e.(*Like)

Notice the *, matching your variable declaration var l *Like.

Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33