Files
the-way-to-go_ZH_CN/eBook/18.5.md
Haigang Zhou fa1cfcc67f 第十七十八章 (#833)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-19 19:57:23 +08:00

951 B
Raw Blame History

18.5 接口

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

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

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

func classifier(items ...interface{}) {
    for i, x := range items {
        switch x.(type) {
        case bool:
            fmt.Printf("param #%d is a bool\n", i)
        case float64:
            fmt.Printf("param #%d is a float64\n", i)
        case int, int64:
            fmt.Printf("param #%d is an int\n", i)
        case nil:
            fmt.Printf("param #%d is nil\n", i)
        case string:
            fmt.Printf("param #%d is a string\n", i)
        default:
            fmt.Printf("param #%ds type is unknown\n", i)
        }
    }
}

链接