CSDN找的一个网页,照着抄练一次。
差不多的使用场景都在了。
package main import ( "fmt" ) type People interface { ReturnName() string } type Role interface { People ReturnRole() string } type Student struct { Name string } type Teacher struct { Name string } func (s Student) ReturnName() string { return s.Name } func (t *Teacher) ReturnName() string { return t.Name } func (s Student) ReturnRole() string { return "student" } func CheckPeople(test interface{}) { if _, ok := test.(People); ok { fmt.Println("Student implements People") } } func main() { cbs := Student{Name: "This is a student."} sss := Teacher{Name: "This is a teacher."} CheckPeople(cbs) var a People var b Role a = cbs name := a.ReturnName() fmt.Println(name) a = &sss name = a.ReturnName() fmt.Println(name) b = cbs role := b.ReturnRole() fmt.Println(role) Params := make([]interface{}, 3) Params[0] = 88 Params[1] = "This is a string" Params[2] = Student{Name: "cbs"} for index, v := range Params { if _, ok := v.(int); ok { fmt.Printf("Params[%d] is int type\n", index) } else if _, ok := v.(string); ok { fmt.Printf("Params[%d] is string type\n", index) } else if _, ok := v.(Student); ok { fmt.Printf("Params[%d] is custom Student type\n", index) } else { fmt.Printf("list[%d] unknown type.\n", index) } } for index, v := range Params { switch value := v.(type) { case int: fmt.Printf("Params[%d] is int type: %d\n", index, value) case string: fmt.Printf("Params[%d] is string type: %s\n", index, value) case Student: fmt.Printf("Params[%d] is custom Student type: %s\n", index, value) default: fmt.Printf("list[%d] unknown type.\n", index) } } }
输出:
D:/go-project/src/InterfaceGo/InterfaceGo.exe [D:/go-project/src/InterfaceGo] Student implements People This is a student. This is a teacher. student Params[0] is int type Params[1] is string type Params[2] is custom Student type Params[0] is int type: 88 Params[1] is string type: This is a string Params[2] is custom Student type: {cbs} 成功: 进程退出代码 0.
原文地址:https://www.cnblogs.com/aguncn/p/11713897.html
时间: 2024-10-27 12:59:28