Kalan's Blog

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

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

Golang Notes — Type Assertion

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