mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Type Switch

A type switch compares types rather than values, it’s used to make several type assertions at once.

go
// The syntax is similar to a type assertion except the keyword `type`
// is used instead of a specific type.
switch x.(type) {
  // cases
}

A type switch can be used to discover the dynamic type of an interface variable.

go
var i any // interface{}

// A function that can return values of different types.
i = GetUnknownValue()

// A type switch is similar to a regular switch statement
// except that the cases specify types and not values.
switch v := i.(type) {
case int:
  // v is of type int
case *int:
  // v is a pointer to int
case string:
  // v is of type string
default:
  // No cases matched
}