Sobes.tech
Junior

How to convert an interface to another type?

sobes.tech AI

Answer from AI

In Golang, type assertions are used to convert an interface to another type.

There are two forms of type assertion:

  1. With success check:

    // Interface example
    var i interface{} = "hello"
    
    // Conversion to string with check
    s, ok := i.(string)
    if ok {
        // Conversion succeeded, use s
    } else {
        // Conversion failed, i is not a string
    }
    

    Here, i.(T) attempts to convert the interface value i to type T. s will contain the converted value, and ok is a boolean indicating success. This method is preferred because it is safe and allows handling the case when conversion is not possible without panicking.

  2. Without success check:

    // Interface example
    var i interface{} = 123
    
    // Conversion to int without check (dangerous, may cause panic)
    n := i.(int)
    

    This form also attempts to convert i to type T, but in case of failure, it causes a panic. Use it only if you are absolutely sure that the interface value has the expected type.

You can also use a switch statement with type assertion to handle multiple possible types:

// Interface example
var i interface{} = true

// Using switch with type assertion
switch v := i.(type) {
case int:
    // i is int, v has type int
case string:
    // i is string, v has type string
case bool:
    // i is bool, v has type bool
default:
    // Unknown type
}

In this case, v inside each case will have a static type corresponding to the checked type.

It is important to remember that:

  • Type assertion checks the concrete underlying type of the value stored in the interface, not whether it implements a specific interface.
  • An empty interface (interface{}) can hold any value, but to access this value, a type assertion or switch is still required.