User Tools

Site Tools


go:data_structures:type_switch

Type switch

What is it?

A type switch lets you execute different code depending on the concrete type stored inside an interface value at runtime.

Syntax: `switch v := i.(type) { … }`

What is it used for?

  • Handle multiple possible concrete types in one function.
  • Safely branch logic without multiple chained type assertions.
  • Implement polymorphic behavior for `any` / `interface{}` inputs.

Example

package main
 
import "fmt"
 
func handle(i any) {
    switch v := i.(type) {
    case int:
        fmt.Println("int:", v+1)
    case string:
        fmt.Println("string:", v+"!")
    default:
        fmt.Println("unknown type")
    }
}
 
func main() {
    handle(10)
    handle("go")
    handle(true)
}

Notes / pitfalls

  • A type switch works only on interface values (including `any`).
  • The variable `v` inside each case has the concrete type for that case.
  • Use type switches sparingly—prefer interfaces with methods when possible.

Hard words (English)

  • type switch /taɪp swɪtʃ/: switch theo kiểu
  • concrete type /ˈkɑːnkriːt taɪp/: kiểu thật bên trong interface
  • interface /ˈɪntərfeɪs/: giao diện
  • runtime /ˈrʌntaɪm/: lúc chương trình đang chạy
  • polymorphic /ˌpɑːlɪˈmɔːrfɪk/: đa hình
  • sparingly /ˈsperɪŋli/: dùng hạn chế
go/data_structures/type_switch.txt · Last modified: by phong2018