Here is my code http://play.golang.org/p/h0N4t2ZAKQ
package main
import (
"fmt"
"reflect"
)
type Msg struct {
Message string
}
func print(y interface{}) {
z, ok := y.(Msg)
fmt.Println(reflect.TypeOf(z))
fmt.Println("Value of ok ", ok)
if ok {
fmt.Println("Message is "+ z.Message)
}
}
func main() {
foo := new(Msg)
foo.Message="Hello"
fmt.Println("Messege in main "+foo.Message)
print(foo)
}
When I run it z.Message does not print Hello Not sure why. Can someone clarify? Thanks in advance
Type of foo
in your program is *Msg
(pointer to Msg), not Msg
. You need to cast y
to *Msg
in print
(http://play.golang.org/p/MTi7QhSVQz):
z, ok := y.(*Msg)
Alternatively you can use Msg
type for foo
(http://play.golang.org/p/XMftjVtzBk):
foo := Msg{Message: "Hello"}
or
var foo Msg
foo.Message = "Hello"
If you run your program, one thing that you will notice is that value of "ok" is false and that's the reason for your print statement in if not getting executed. If you remove "ok" from z, ok := y.(Msg), you will see the error that Go is throwing while executing this assert statement. With ok, Go will not panic and will return false if assertion fails. Which is happening in your case.
The reason for asserting failing is, expected, type in print method is Msg(main.Msg), but passed is pointer i.e. *main.Msg. You will see this error when you don't use "ok"
So one way is to
print(*foo)
Or
z, ok := y.(*Msg)