'How to 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?
Solution 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Burak Serdar |
