Sobes.tech
Middle

Type Assertion — what is the purpose of this construct?

sobes.tech AI

Answer from AI

In Go, the Type Assertion construct is used to extract a specific type from an interface value. It allows checking and obtaining the value of a certain type if it is known that the interface contains exactly that type.

Syntax:

value, ok := interfaceValue.(ConcreteType)
  • value — a variable of type ConcreteType, into which the value will be stored.
  • ok — a boolean indicating whether the type check was successful.

If ok is true, it means interfaceValue contains a value of type ConcreteType, and it can be used.

Example:

var i interface{} = "hello"

str, ok := i.(string)
if ok {
    fmt.Println("String:", str)
} else {
    fmt.Println("i does not contain a string")
}

Attempting to assert without checking ok and if the type does not match will cause a panic:

str := i.(string) // panic if i is not a string

Thus, Type Assertion is used for safe extraction of a specific type value from an interface value, which is often used when working with interfaces and dynamic types.

Type Assertion — what is the purpose of this… - sobes.tech