if v, ok := v.(Stringer); ok { fmt.Printf("implements String(): %s\n", v.String()) }
(2)如何使用接口实现一个类型分类函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcclassifier(items ...interface{}) { for i, x := range items { switch x.(type) { casebool: fmt.Printf("param #%d is a bool\n", i) casefloat64: fmt.Printf("param #%d is a float64\n", i) caseint, int64: fmt.Printf("param #%d is an int\n", i) casenil: fmt.Printf("param #%d is nil\n", i) casestring: fmt.Printf("param #%d is a string\n", i) default: fmt.Printf("param #%d’s type is unknown\n", i) } } }