Golang use reflect interface{} to struct{}
If you just want to know how to convert interface{}
to struct{}
, the code just as below:
interface.(*Struct)
you can use reflect.ValueOf
to get the value of interface, then use Interface()
to get the interface
of the value. In this case, assume you don't know what the type of your interface{}
:
type Human interface {
Name() string
Type() string
}
type Martian struct {
name string
id int
}
func (m *Martian) Name() string {
return m.name
}
func (m *Martian) Type() string {
return "martian"
}
func TestHuman(t *testing.T) {
var human Human
human = &Martian{
name: "Jack",
id: 1,
}
t.Log(human.Name())
// convert interface{} to struct{}
obj := reflect.ValueOf(human)
martian := obj.Interface().(*Martian)
t.Log(martian.id)
}