18.5 接口

(1)如何检测一个值 v 是否实现了接口 Stringer

  1. if v, ok := v.(Stringer); ok {
  2. fmt.Printf("implements String(): %s\n", v.String())
  3. }

(2)如何使用接口实现一个类型分类函数:

  1. func classifier(items ...interface{}) {
  2. for i, x := range items {
  3. switch x.(type) {
  4. case bool:
  5. fmt.Printf("param #%d is a bool\n", i)
  6. case float64:
  7. fmt.Printf("param #%d is a float64\n", i)
  8. case int, int64:
  9. fmt.Printf("param #%d is an int\n", i)
  10. case nil:
  11. fmt.Printf("param #%d is nil\n", i)
  12. case string:
  13. fmt.Printf("param #%d is a string\n", i)
  14. default:
  15. fmt.Printf("param #%d’s type is unknown\n", i)
  16. }
  17. }
  18. }

链接