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()
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
A type assertion provides access to an interface value's underlying concrete value. t := i.(T) This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t . If i does not hold a T , the statement will trigger a panic.
The interface type that specifies zero methods is known as the empty interface: interface{} An empty interface may hold values of any type. (Every type implements at least zero methods.) Empty interfaces are used by code that handles values of unknown 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With