Sobes.tech
Junior — Middle

Selgitage type switch'i tööpõhimõtet Go keeles ja kuidas see erine tavalisest switch-case-st.

sobes.tech AI

Vastus AI-lt

In the Go language, the type switch construct is used to determine the specific type of an interface value at runtime. It allows performing different actions depending on the type to which the variable implementing the interface belongs.

Syntax example:

switch v := x.(type) {
case int:
    fmt.Println("int", v)
case string:
    fmt.Println("string", v)
default:
    fmt.Println("other type")
}

Here, x is a variable of interface type, and v is a variable with a specific type within each case.

Difference from a regular switch-case:

  • A regular switch compares the value of the expression with constants or expressions.
  • The type switch compares the type of the interface value, not the value itself.

The type switch is useful when working with interfaces, where you need to perform different actions depending on the actual type of the object stored in the interface.