当前位置: 首页 > 文档资料 > Go 入门指南 >

18.5 接口

优质
小牛编辑
134浏览
2023-12-01

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

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

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

func classifier(items ...interface{}) {
    for i, x := range items {
        switch x.(type) {
        case bool:
            fmt.Printf("param #%d is a booln", i)
        case float64:
            fmt.Printf("param #%d is a float64n", i)
        case int, int64:
            fmt.Printf("param #%d is an intn", i)
        case nil:
            fmt.Printf("param #%d is niln", i)
        case string:
            fmt.Printf("param #%d is a stringn", i)
        default:
            fmt.Printf("param #%d’s type is unknownn", i)
        }
    }
}