Home > Mobile >  How to assert type is a pointer to an interface in golang
How to assert type is a pointer to an interface in golang

Time:03-31

I am asserting that the type of a pointer to a struct is implementing an interface in golang and there is something I don't understand in the code sample below:

package main

import (
    "fmt"
)

type MyStruct struct {
    Name string
}

func (m *MyStruct) MyFunc() {
    m.Name = "bar"
}

type MyInterface interface {
    MyFunc()
}

func main() {
    x := &MyStruct{
        Name: "foo",
    }
    var y interface{}
    y = x
    _, ok := y.(MyInterface)
    if !ok {
        fmt.Println("Not MyInterface")
    } else {
        fmt.Println("It is MyInterface")
    }
}

I was expecting to do _, ok := y.(*MyInterface) since y is a pointer to MyStruct. Why can't I assert it is a pointer?

CodePudding user response:

Type assertion is used to find the type of the object contained in an interface. So, y.(MyInterface) works, because the object contained in the interface y is a *MyStruct, and it implements MyInterface. However, *MyInterface is not an interface, it is a pointer to an interface, so what you are asserting is whether y is a *MyInterface, not whether or not y implements MyInterface. This will only be successful if:

var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)
  •  Tags:  
  • go
  • Related