Home > Backend Development > Golang > How to Handle \'Invalid Operation: Type Interface {} Does Not Support Indexing\' Errors in Go?

How to Handle \'Invalid Operation: Type Interface {} Does Not Support Indexing\' Errors in Go?

DDD
Release: 2024-10-26 09:48:29
Original
879 people have browsed it

How to Handle

Indexing Interface Interfaces: Addressing Interface {} Indexing Error

When working with nested JSON responses, it's not uncommon to encounter the error "invalid operation: type interface {} does not support indexing." This arises when attempting to access nested values in an interface typed variable, but the correct type assertion isn't applied.

Consider the following example, assuming a JSON response like the one provided:

<code class="go">var d interface{}
json.NewDecoder(response.Body).Decode(&d)
test := d["data"].(map[string]interface{})["type"]</code>
Copy after login

The line attempting to access the "type" value throws the indexing error because d is of type interface{}, which doesn't support array-like indexing. To resolve this, we need to type assert d to the appropriate type, in this case, a map[string]interface{}:

<code class="go">test := d.(map[string]interface{})["data"].(map[string]interface{})["type"]</code>
Copy after login

This nested type assertion allows us to access the "type" value successfully.

Alternatively, you can specify the type of d as map[string]interface{} from the start:

<code class="go">var d map[string]interface{}
json.NewDecoder(response.Body).Decode(&d)
test := d["data"].(map[string]interface{})["type"]</code>
Copy after login

By declaring d as a map[string]interface{}, the first type assertion is redundant.

Additionally, if performing similar operations repeatedly, consider using the github.com/icza/dyno library to facilitate working with dynamic objects.

The above is the detailed content of How to Handle \'Invalid Operation: Type Interface {} Does Not Support Indexing\' Errors 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template