Home > Backend Development > Golang > How to Correctly Type Assert a Slice of Interface Values in Go?

How to Correctly Type Assert a Slice of Interface Values in Go?

Linda Hamilton
Release: 2024-12-30 18:17:11
Original
790 people have browsed it

How to Correctly Type Assert a Slice of Interface Values in Go?

Type Assertion of Interface Slice Values

When attempting to type assert a slice of interface values, such as []Node, to another type, such as []Symbol, you may encounter the error "invalid type assertion." This error arises because a slice is a distinct, non-interface type. Type checking relies on the notion that a variable's dynamic type remains fixed for interface types, but not for slices or other non-interface types.

Therefore, the statement args.([]Symbol) in the provided code fails because args is of type []Node, which is not an interface type. To type assert properly, you should first convert the slice elements to the desired type, as shown in the following code:

symbols := make([]Symbol, len(args))
for i, arg := range args { symbols[i] = arg.(Symbol) }
fixed, rest := parseFormals(symbols)
Copy after login

This modified code creates an array of Symbol values and iterates over the original []Node slice, type asserting each element to Symbol. After obtaining the desired []Symbol slice, you can perform the necessary operations without encountering type assertion errors.

The above is the detailed content of How to Correctly Type Assert a Slice of Interface Values in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template