在 golang 中 interface{} 可用于向函数传递任意类型的变量, 但在函数内部使用的话, 该变量的类型就是 interface{}, 也称为空接口类型
比如我们定义一个函数, 输出字符串, 但参数是 interface{} 类型
func echoString(content interface{}) {
mt.Println(content )
}
当我们调用 echoString("输出字符串") 方法, 会报错因为content是interface{}类型, 而不是string类型
接口类型向普通类型的转换称为类型断言(运行期确定)
对于上述调用, 可以通过修改方法echoString
func echoString(content interface{}) {
result, _ := content.(string) //通过断言实现类型转换
fmt.Println(result)
}
这个时候又会有潜在的威胁, 如果我们给该方法传入的是 int 类型, 那么在断言的时候会报错, 这个时候我们需要完善代码
func echoString(content interface{}) {
result, err := content.(string)
if err != nil { // 断言失败
fmt.Println(err .Error()) // 输出失败原因
return
}
fmt.Println(result)
}
不同类型变量的运算必须进行显式的类型转换,否者结果可能出错
Type assertion
x.(T), if T is a concrete type,
it will check if x's dynamic type is identical to T, if so the results is the dynamic value, or it will panic. If the T is a interface type, it will first check if x's dynamic type satisfies T, if so, a new interface value will be returned with the new dynamic type T and the same dynamic value.
No matter what type was asserted, if the operand is a nil interface value, the type assertion fails
Type switch
take one example, you can assign the x.(type) to a new variable
func sqlQuote(x interface{}) string {
switch x := x.(type) {
case nil:
return "NULL"
case int, uint:
return fmt.Sprintf("%d", x) // x has type interface{} here.
case bool:
if x {
return "TRUE"
}
return "FALSE"
case string:
return sqlQuoteString(x) // (not shown)
default:
panic(fmt.Sprintf("unexpected type %T: %v",wxw,wx.i)t)-ebooks.info }
}
网友评论