Go
The empty interface is used interface {}
to indicate that it can be of any type, so that if this 变量
type needs to be detected, then it is necessary 类型断言
.
val,ok := varl.(Type)
val
It must be a variable of an excuse type, otherwise an error will be reported when compiling.
Type
is a concrete type.
This assertion expression returns a val
and a Boolean type ok
, according to ok
whether varl
it belongs to Type
the type.
- If
Type
it is a concrete type, the type assertionvarl
checks whether the dynamic type of is equal to the concrete typeType
. If the check succeeds, the result returned by the type assertion is the dynamic valuevarl
of , whose type isType
. - If
Type
is an interface type, the type assertion checksvarl
whether the dynamic type of is satisfiedType
. If the check is successful,varl
the dynamic value of is not extracted, and the return value is an interface valueType
of . - Regardless
Type
of the type of , ifvarl
is a nil interface value, the type assertion will fail.
package main
import (
"fmt"
)
func main() {
//定义一个任意类型的变量
var site interface{
}
site = "https://qiucode.cn"
web, ok := site.(string)
fmt.Println(web, ok)
}
Type assertions can switch
be used in conjunction.
package main
import (
"fmt"
)
func getType(t interface{
}) {
switch t.(type) {
case string:
fmt.Println("该类型为 string ")
case int:
fmt.Println("该类型是 int ")
case float64:
fmt.Println("该类型为 float64 ")
default:
fmt.Println("暂没有匹配的类型")
}
}
func main() {
//定义一个任意类型的变量
var site interface{
}
site = "https://qiucode.cn"
getType(site)
}