Home >Backend Development >Golang >Type Assertion in Go: Why 'Cannot Type Switch on Non-Interface Value' and How to Fix?
Type Assertion in Go: Resolving the "Cannot Type Switch on Non-Interface Value" Error
When working with type assertions in Go, it's possible to encounter the error "cannot type switch on non-interface value." Let's delve into what this means and how to resolve it, with an example using a custom type.
Consider the following code snippet:
package main import "fmt" import "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 := n.(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
When you run this code, you'll encounter the error "cannot type switch on non-interface value." This indicates that the type assertion is being performed on a non-interface value. In this case, n is a pointer to a Number struct, which is not an interface.
The solution is to cast the value to an interface{} before attempting the type assertion. This is because type assertions can only be performed on interface values. Here's the corrected code:
func main() { n := &Number{1} switch v := interface{}(n).(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
Now, when you run the code, it will print "Stringer: 1." This is because casting n to interface{} allows it to be treated as an interface value for type assertion.
The above is the detailed content of Type Assertion in Go: Why 'Cannot Type Switch on Non-Interface Value' and How to Fix?. For more information, please follow other related articles on the PHP Chinese website!