This is a creation in Article, where the information may have evolved or changed.
Golang type conversion/type assertion/type switching
1. Type Assertion
Type assertion is the value of the interface type that is loaded into the (x)
type (T)
. The format is:
x.(T)v:=x.(T)v,ok:=x.(T)
the necessary condition for type assertion is that x is an interface type and x
cannot be a type assertion for a non-interface type :
var i int=10v:=i.(int) //错误 i不是接口类型
T
Can be a non-interface type, and if you want to assert legitimacy, you T
should implement x
an interface
T
can also be an interface, x
the dynamic type should also implement the interfaceT
var x interface{}=7 //x的动态类型为int,值为7i:=x.(int) // i的类型为int ,值为7type I interface {m()}var y Is:=y.(string) //非法: string 没有实现接口 I (missing method m)r:=y.(io.Reader) //y如果实现了接口io.Reader和I的情况下, r的类型则为io.Reader
If the type assertion is illegal, the runtime will have an error, and in order to avoid this error, you can use the syntax:
v,ok:=x.(T)
ok
Represents whether the type assertion is legal, if it is illegal, so that it ok
false
does not appear panic
2. Type switchingtype switch
type switching is used to compare types instead of comparing values
type switch
It is used to detect whether the type of a value x
T
matches a type.
The format is similar to the type assertion, but the parentheses are not a specific type, but a word type
:
switch x.(type){ }
type switch
A statement can have a shorthand variable declaration, in which case it is equivalent to the variable declared at the case clause
beginning of each implicit code block. If only one type is listed, the type of the variable is that type case clause
, otherwise it is the type of the original value
Suppose the following example is of the x
type x interface{}
:
switch i := x.(type) {case nil: printString("x is nil") // i的类型是 x的类型 (interface{})case int: printInt(i) // i的类型 intcase float64: printFloat64(i) // i的类型是 float64case func(int) float64: printFunction(i) // i的类型是 func(int) float64case bool, string: printString("type is bool or string") // i的类型是 x (interface{})default: printString("don't know the type") // i的类型是 x的类型 (interface{})}
You may have seen in the example above that the type in case clause is nil, and it is used to match interface{} with x nil.
The results of the operation are as follows:
Reference article: http://colobu.com/2016/06/21/...