logo
  • 現在做什麼
  • 關於我

Kalan

文章分類

  • 前端
  • 開發筆記
  • 雜談
  • 年度回顧

快速連結

  • 現在做什麼
  • 關於我
  • 聯絡我
  • 職涯思考🔗

關注我

在福岡生活的開發者,分享軟體開發與日本生活的點點滴滴。

© 2025 Kalan Made with ❤️. All rights reserved.

Golang Notes — Type Assertion

Written byKalanKalanMar 29, 2019
Home/Dev Note
💡

If you have any questions or feedback, pleasefill out this form

Japanese原文

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:

    1. 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.
    2. 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.

    ← Introduction to Goworker — Implementing Workers with RedisHow to collect and centralize logs in golang app →

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

    ☕Buy me a coffee