Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot assert type is a pointer to an interface in golang

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading