Home > Backend Development > Golang > Go: Why Am I Getting 'Invalid Operation: type *map[key]value does not support indexing.'?

Go: Why Am I Getting 'Invalid Operation: type *map[key]value does not support indexing.'?

Mary-Kate Olsen
Release: 2024-11-12 04:53:01
Original
347 people have browsed it

Go: Why Am I Getting

Go: Addressing "Invalid Operation" Error in Map Indexing

When working with maps in Go, you may encounter the compiler error "invalid operation: type *map[key]value does not support indexing." This error occurs when you attempt to index a pointer to a map instead of the map itself.

Consider the following code:

func (b *Balance) Add(amount Amount) *Balance {
    current, ok := b[amount.Currency] // Error: indexing pointer to map
    ...
}
Copy after login

To resolve this error, you should modify your code to index the map through the pointer correctly:

func (b *Balance) Add(amount Amount) *Balance {
    current, ok := (*b)[amount.Currency] // Index the map through the pointer
    ...
}
Copy after login

Alternatively, if your struct is solely a map, it's recommended to avoid defining methods that receive map pointers as they offer no benefit. Instead, define methods that receive the map by value, as shown below:

import "fmt"

type Currency string

type Amount struct {
    Currency Currency
    Value float32
}

type Balance map[Currency]float32

func (b Balance) Add(amount Amount) Balance { // Method receives map by value
    current, ok := b[amount.Currency]
    ...
}

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

This approach avoids the error associated with indexing a map through a pointer while maintaining the reference nature of the map type.

The above is the detailed content of Go: Why Am I Getting 'Invalid Operation: type *map[key]value does not support indexing.'?. 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