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"