package mainimport ( "fmt")type User struct { Id int Name string}type Tester interface { Test()}func (this *User) Test() { fmt.Println("*User.Test", this)}func doSomething(i interface{}) { if o, ok := i.(Tester); ok { //检查 o.Test() } // i.(*User).Test()}func main() { u := &User{1, "Tom"} doSomething(u)}
package mainimport ( "fmt")type User struct { Id int Name string}func Test(i interface{}) { switch v := i.(type) { case *User: fmt.Println("User : Name = ", v.Name) case string: fmt.Println("string = ", v) default: fmt.Printf("%T : %v \n", v, v) }}func main() { Test(&User{1, "Tom"}) Test("hello world") Test(123)}