Home >Backend Development >Golang >How to Safely Type Assert from a Slice of Interface Values in Go?
Type Assertion from a Slice of Interface Values
In Go, attempting to type assert from a slice of interface values, such as []Node to []Symbol, can result in an error. While Symbol implements the Node interface, the slice []Node is not an interface type.
The error message, "invalid type assertion: args.([]Symbol) (non-interface type []Node on left)," indicates that the slice of interface values ([]Node) cannot be directly asserted to an interface type ([]Symbol).
Reason
A slice is a distinct, non-interface type with its own set of methods. It doesn't inherit methods from the elements it contains, unlike an interface. Therefore, it doesn't make sense to assume that a slice of interface values is an interface itself.
Solution
To properly type assert in this situation, you can use a loop to convert each element of the slice into the desired type. For example, the following code:
symbols := make([]Symbol, len(args)) for i, arg := range args { symbols[i] = arg.(Symbol) } fixed, rest := parseFormals(symbols)
Creates a new slice of Symbol values, symbols, and iterates over the args slice, converting each element to a Symbol type. You can then use symbols for further processing.
Remember, type assertions should only be used when you're absolutely certain that the assertion will succeed. Otherwise, a panic may occur at runtime.
The above is the detailed content of How to Safely Type Assert from a Slice of Interface Values in Go?. For more information, please follow other related articles on the PHP Chinese website!