Golang Notes — Type Assertion
In golang, for values of type interface{}, you can use a type assertion to assert that the interface holds a specific concrete type. This allows you to access the underlying value and call methods defined on that type.
var i interface{} = "hello"
s := i.(string)
fmt.Println(s)
This snippet asserts the original interface{} as a string.
However, note that if the underlying type is not a string, this code will panic immediately.
args := []interface{}{
1,
"1",
"2",
}
for _, arg := args {
val := arg.(int) // interface conversion: interface {} is string, not int
fmt.Println(val)
}
Golang provides a mechanism where a type assertion can return 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.")
}
}
At this point, there are two key takeaways to keep in mind:
- Without the second return value, your program may panic if the assertion fails, unless you are absolutely sure of the type.
- Checking the second return value prevents the program from raising a
panic.
Although it takes a bit more boilerplate, it is always safer to use the two-value form.
Another thing to note is that when the assertion fails, val will be the zero-value of the asserted type.
When the assertion fails, val 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 speaking, you rarely need to use this value after an assertion fails, but careless handling could still lead into a trap.
Related Posts
- When a Measure Becomes a Target: From the Window Tax to Pull Request Counts I once wrote a script to tally how many PRs I contributed in a quarter, how many reviews I left, and how many tickets I closed, hoping to use numbers to prove my output to my manager. My manager simply remarked that performance isn't just about output. Years later, I finally understood—when a measure becomes a target, it ceases to be a good measure. From the British window tax and the Hanoi rat bounty to evaluating developers by PR counts today, the underlying mechanism is exactly the same.
- Using Cloudflare Images for Image Storage and Transformation Putting an image on a webpage is the simplest task in frontend development. But doing it properly—including resizing, generating multiple formats, and withstanding heavy traffic—is actually an entire end-to-end solution. Eventually, I offloaded everything to Cloudflare Images, keeping only a single original image.
- Stop Using AWS Access Keys Access Keys are an easily overlooked security risk in AWS. By pairing OIDC with IAM Roles, GitHub Actions can securely operate AWS resources without storing any secrets.
- Database Primary Keys: AUTO_INCREMENT, UUID, and UUIDv7 Backend developers often face the choice of primary keys: should you use auto-increment or UUID? What about collisions? How does UUIDv7 compare to created_at + index in performance? Here are the design decisions and benchmark results from testing 20 million rows.