Home >Backend Development >Golang >Why does my Go code throw a 'cannot type switch on non-interface value' error?
Understanding Type Switch Errors
In Go, using a type switch on a non-interface variable results in the error "cannot type switch on non-interface value." To resolve this issue, it's necessary to cast the variable to an appropriate interface type before attempting the type switch.
In the given example, the code attempts to perform a type switch on the variable n, which is an instance of the Number struct. However, the Number struct does not implement any interface, so it cannot be used directly in a type switch.
Resolving the Error
To fix the error, you must first cast n to the interface{} type, which represents an empty interface. This converts n into a value that can hold any type. Then, within the type switch, you can assert the actual type of the underlying value using the type keyword.
Here's how the corrected code would look:
import ( "fmt" "strconv" ) type Stringer interface { String() string } type Number struct { v int } func (number *Number) String() string { return strconv.Itoa(number.v) } func main() { n := &Number{1} switch v := interface{}(n).(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
With this change, the code successfully prints "Stringer: 1".
The above is the detailed content of Why does my Go code throw a 'cannot type switch on non-interface value' error?. For more information, please follow other related articles on the PHP Chinese website!