Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

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:

  1. If there is no second return value, unless you are certain about the type, the program may panic due to failed assertion.
  2. 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.

Prev

Introduction to Goworker — Implementing Workers with Redis

Next

How to collect and centralize logs in golang app

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.