Home > Backend Development > Golang > Why Can't I Use Pointer Receivers on Map Entries in Go?

Why Can't I Use Pointer Receivers on Map Entries in Go?

Barbara Streisand
Release: 2024-12-21 02:00:14
Original
226 people have browsed it

Why Can't I Use Pointer Receivers on Map Entries in Go?

Dereferencing a Map Index in Go

Within a Go program, map indices cannot be referenced directly. This issue arises due to the dynamic nature of maps, where the address of an entry may change during map growth or shrinkage. As a result, attempting to call pointer receiver methods on map entries leads to the following error:

cannot call pointer method on f[0]
cannot take the address of f[0]
Copy after login

To resolve this issue, simply remove the asterisk (*) from the method receiver in the problematic method:

func (c Cashier) Buy(itemNum int){
    item, pass := c.items[itemNum]

    if pass{
        if item.amount == 1{
            delete(c.items, itemNum)
        } else{
            item.amount--
            c.items[itemNum] = item 
        }
        c.cash++
    }
}
Copy after login

By doing so, the method is no longer a pointer receiver, allowing it to be called on map entries without issue.

The above is the detailed content of Why Can't I Use Pointer Receivers on Map Entries 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