In golang
, for the type interface{}
, you can perform type assertion to assume that the interface is of a certain type. This way, you can manipulate the methods of that type.
var i interface{} = "hello"
s := i.(string)
fmt.Println(s)
This code snippet asserts the original interface{}
as a string.
However, it is important to note that if the type is not a string, this code will panic.
args := []interface{}{
1,
"1",
"2",
}
for _, arg := args {
val := arg.(int) // interface conversion: interface {} is string, not int
fmt.Println(val)
}
In golang, there is a mechanism where type assertion returns two values: the converted value and a boolean indicating whether the assertion was successful.
args := []interface{}{
1,
"1",
"2",
}
for _, arg := args {
if val, ok := arg.(int); ok {
fmt.Println(val)
} else {
fmt.Println("not int.")
}
}
Here, there are two points to note:
- If there is no second return value, unless you are certain about the type, the program may panic due to failed assertion.
- Adding the second return value does not cause a panic.
Although it may be a bit cumbersome, it is always safer to perform type conversion.
Another point to note is that the val
after a failed assertion will be the zero value of the asserted type.
The val
after a failed assertion will be the zero value of the asserted type.
for _, arg := range args {
if val, ok := arg.(int); ok {
fmt.Println(val, ok) // 1, true
} else {
fmt.Println(val, ok) // 0 , false
// 0, false
}
}
Generally, after a failed assertion, you don't often use this value. However, you may still fall into a trap if you're not careful.