type Human struct {
Name string
}
func (t *Human) GetInfo() {
fmt.Println(t.Name)
}
func main() {
var p1 interface{}
p1 = Human{Name:"John"}
//p1.GetInfo()
}
now,p1's typs is interface{}, but i want get a Human object.
How to do? i can call p1.GetInfo()
You can do a type assertion inline:
p1.(*Human).GetAll()
http://play.golang.org/p/ldtVrPnZ79
Or you can create a new variable to hold a Human type.
You can use a type assertion to unwrap the value stored in an interface variable. From your example, p1.(Human)
would extract a Human
value from the variable, or panic if the variable held a different type.
But if your aim is to call methods on whatever is held in the interface variable, you probably don't want to use a plain interface{}
variable. Instead, declare the methods you want for the interface type. For instance:
type GetInfoer interface {
GetInfo()
}
func main() {
var p1 GetInfoer
p1 = &Human{Name:"John"}
p1.GetInfo()
}
Go will then make sure you only assign a value with a GetInfo
method to p1
, and make sure that the method call invokes the method appropriate to the type stored in the variable. There is no longer a need to use a type assertion, and the code will work with any value implementing the interface.