Home > Backend Development > Golang > Why Does Type Assertion Fail on a Slice of Interface Values?

Why Does Type Assertion Fail on a Slice of Interface Values?

DDD
Release: 2024-12-07 14:13:15
Original
801 people have browsed it

Why Does Type Assertion Fail on a Slice of Interface Values?

Type Assertion of a Slice of Interface Values

In attempting to type assert from a slice of Node to a slice of Symbol, an error is encountered indicating that the type assertion is invalid. This is because a slice of interface values is not itself an interface type.

A slice is a distinct, non-interface type, while an interface type defines a set of methods. Therefore, it does not make sense to assume that a slice of interface values is also an interface type.

To resolve this issue, instead of type asserting the slice of Node directly, you can convert each element of the slice to the desired type, Symbol in this case, and create a new slice of the desired type. For example, the following code would achieve the desired result:

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

The above is the detailed content of Why Does Type Assertion Fail on a Slice of Interface Values?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template