Why Do I Get 'Invalid Operation - Type *map[key]value Does Not Support Indexing' in Go?

Susan Sarandon
Release: 2024-11-14 11:08:02
Original
301 people have browsed it

Why Do I Get

Go: Invalid Operation - Type *map[key]value Does Not Support Indexing

In Go, attempts to pass a map by pointer and modify the original map through the pointer may result in an "invalid operation" error. This is because indexing on a pointer to a map is not supported in Go.

To resolve this issue, it is necessary to index on the map itself rather than the pointer. Here's a modified code that demonstrates how to do this:

package main

import "fmt"

type Currency string

type Amount struct {
    Currency Currency
    Value float32
}

type Balance map[Currency]float32

func (b *Balance) Add(amount Amount) *Balance {
    current, ok := (*b)[amount.Currency]
    if ok {
        (*b)[amount.Currency] = current + amount.Value
    } else {
        (*b)[amount.Currency] = amount.Value
    }
    return b
}

func main() {
    b := &Balance{Currency("USD"): 100.0}
    b = b.Add(Amount{Currency: Currency("USD"), Value: 5.0})

    fmt.Println("Balance: ", (*b))
}
Copy after login

By dereferencing the pointer to the map (*b) before indexing, the code now correctly modifies the original map.

Note: While the above code demonstrates how to modify a map through a pointer, it is generally more idiomatic to pass the map by value in Go. By passing a value, changes made to the map are automatically propagated back to the original map.

The above is the detailed content of Why Do I Get 'Invalid Operation - Type *map[key]value Does Not Support Indexing' 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