Search code examples
gogo-map

Check if a value exists in map using an internal function from that struct


I've this struct

type Zones map[uint64]Zone

And I want to have a method to find a value in that map, something like this.

func (z *Zones) findById(id uint64) (Zone, error) {
    if zone, ok := z[id]; ok {
        return zone, nil
    } else {
        return zone{}, errors.New(fmt.Sprintf("Zone %d not found", id))
    }
}

But in this line:

if zone, ok := z[id]; ok {

I'm getting this error:

Assignment count mismatch: 2=1.

Theres a lot of links which suggest that we can check if a value exists in a map with that line, I have no idea what is happening. What am I doing wrong?

Thanks in advance.


Solution

  • The type *Zone does not support indexing. It's a pointer, not a map. Dereference the pointer to fix the code:

    func (z *Zones) findById(id uint64) (Zone, error) {
        if zone, ok := (*z)[id]; ok { // <-- note change on this line
            return zone, nil
        } else {
            return Zone{}, errors.New(fmt.Sprintf("Zone %d not found", id))
        }
    }