Home > Article > Backend Development > Why Does Go Throw a "Cannot Type Switch on Non-Interface Value" Error?
Type Assertion in Go: Resolving "Cannot Type Switch on Non-Interface Value"
In Go, type assertion involves checking if a value belongs to a particular type. When encountering the error "cannot type switch on non-interface value," it means that the value being checked is not an interface.
Consider the following code:
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 := n.(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
This code attempts to type switch on the value n, which is of type *Number. However, it results in the "cannot type switch on non-interface value" error.
To resolve this, we need to cast n to an interface value before performing the type assertion. This is because type switching can only be performed on interface values. The following corrected code demonstrates this:
switch v := interface{}(n).(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") }
By casting n to interface{}, we allow the type switch to be performed on the resulting interface value. This allows us to successfully check if n is of type Stringer and print the corresponding message.
The above is the detailed content of Why Does Go Throw a "Cannot Type Switch on Non-Interface Value" Error?. For more information, please follow other related articles on the PHP Chinese website!