2

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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.