If you have any questions or feedback, pleasefill out this form
Table of Contents
This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.
In golang
, you can perform type assertion on the interface{}
type to assume that this interface is of a specific type. This allows you to invoke methods associated with that type.
var i interface{} = "hello"
s := i.(string)
fmt.Println(s)
This snippet of code asserts that the original interface{}
is a string.
However, it's crucial to note that if the type is not a string, this code will cause a panic.
args := []interface{}{
1,
"1",
"2",
}
for _, arg := range args {
val := arg.(int) // interface conversion: interface {} is string, not int
fmt.Println(val)
}
Golang provides a mechanism where type assertion will return two values: one is the converted value, and the other indicates whether the assertion was successful.
args := []interface{}{
1,
"1",
"2",
}
for _, arg := range args {
if val, ok := arg.(int); ok {
fmt.Println(val)
} else {
fmt.Println("not int.")
}
}
At this point, there are two important things to keep in mind:
- If you don't use the second return value, your program may panic due to a failed assertion unless you are very certain about the type.
- By using the second return value, you can avoid
panic
.
Although it may seem a bit cumbersome, it's generally safer to perform type conversions this way.
Another point to note is that if the assertion fails, the val
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
}
}
Typically, the value after a failed assertion is not commonly used, but it can be a trap if you're not careful.
If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨
☕Buy me a coffee