How to cast interface{} to a given interface?

You’re actually doing this correctly, but the issues lies somewhere else. You declare a method Increment on *I, not I, meaning that method will only be able to be called on a pointer receiver. You’re trying to assert an I to an Incrementor, whereas you should be asserting *I to Incrementor, like so:

package main

type Incrementor interface {
	Increment()
}

type I int

func (i *I) Increment() {
	*i++
}

func main() {
	i := new(I)

	var j interface{} = i
	j.(Incrementor).Increment()
}
1 Like