示例

func main() {
    var i interface{} = "hello"

    s := i.(string)
    fmt.Println(s) // hello

    s, ok := i.(string)
    fmt.Println(s, ok) // hello true

    f, ok := i.(float64)
    fmt.Println(f, ok) // 0 false

    f = i.(float64) // panic 即使是字符串123也会panic 因为类型不同
    fmt.Println(f)
}

类型转换

t := i.(T)interface{}

类型断言后转换

方式一

t, ok := i.(T)interface{}oktruetokfalsetint0string""

方式二

switchobject.(type)
func Cast(object interface{}) {
    switch object.(type) {
    case string:
        fmt.Println("string#", object.(string))
    case int:
        fmt.Println("int#", object.(int))
    case float64:
        fmt.Println("float64#", object.(float64))
        // 其他类型
    }
}

参考