Sobes.tech
Senior

In which type conversion is panic possible and which construct can prevent it?

sobes.tech AI

Answer from AI

Panic can occur when type assertion is used to convert a type, if the actual type of the value does not match the expected type. For example:

var i interface{} = "string"
// Attempting to convert to int will cause a panic
n := i.(int) // panic: interface conversion: interface {} is string, not int

To avoid panic, a two-value assignment is used — the second indicates whether the conversion was successful:

n, ok := i.(int)
if !ok {
    // handle conversion error
}

Thus, a safe type assertion allows avoiding panic and handling the situation correctly when the types do not match.

In which type conversion is panic possible and which… - sobes.tech