Golang Notes — Type Assertion
# Dev NoteIn 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.
Related Posts
- Stop Using Access Keys AlreadyAccess Keys are an easily overlooked security risk on AWS. Use OIDC with IAM Roles so GitHub Actions can securely access AWS resources without any secrets.
- Database Primary Keys: AUTO_INCREMENT, UUID, and UUIDv7Backend developers often have to decide on a primary key: auto increment or UUID? What about collisions? How much faster is UUIDv7 compared with created_at + index? After benchmarking 20 million rows and looking at the design trade-offs, this post gives you the answer.
- Sharing My Experience with ZeaburIndependent developers often choose platforms like Vercel for deploying their services. However, when more advanced requirements arise, such as database connections, Vercel can become less convenient. Additionally, the pricing of typical cloud service providers can be quite expensive for solo developers. In this article, I’ll share some insights on using Zeabur and highly recommend it to everyone!
- Keyboard Enthusiast's Guide - Firmware EditionThis article is part of the IT 2023 Ironman Competition: A Beginner's Guide to Keyboards - Firmware Edition.