Error: "Cannot Type Switch on Non-Interface Value" in Golang
When working with type assertions, you may encounter the error "cannot type switch on non-interface value." This occurs when attempting to perform a type switch on a value that is not an interface.
In Golang, type switching allows you to conditionally execute code based on the type of a variable. However, it requires the variable to be of an interface type. An interface represents a contract that defines a set of methods that an implementing type must implement.
In the provided code snippet, a type named Stringer is defined with a single String() method. The Number type also implements the String() method, making it a concrete implementation of the Stringer interface.
type Stringer interface { String() string } type Number struct { v int } func (number *Number) String() string { return strconv.Itoa(number.v) }
However, the error occurs in the main function, where a type switch is attempted on the n variable, which is of type *Number rather than Stringer.
func main() { n := &Number{1} switch v := n.(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
To resolve this issue, you need to cast n to interface{} before performing the type assertion. This is because interface{} can represent any arbitrary value.
func main() { n := &Number{1} switch v := interface{}(n).(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
By casting n to interface{}, you essentially allow the type switch to consider the possibility that n might be of type Stringer. Once the type switch is entered, the actual type of n can be determined and the appropriate case branch executed.
The above is the detailed content of Why Do I Get the 'Cannot Type Switch on Non-Interface Value' Error in Golang?. For more information, please follow other related articles on the PHP Chinese website!