golang – struct in sync map access

Issue

I am trying to load struct type data arbitrarily defined in sync map. Is there any convenient way to access the map type by defining (like generic, sync.Map[struct]{})?

package main

import (
    "sync"
)

type mystruct struct {
    cnt int
}

func (m *mystruct) Add() {
    m.cnt++
}
func main() {

    m := sync.Map{}
    m.Store("a", &mystruct{1})
    m.Store("b", &mystruct{1})

    v, _ := m.Load("a")
    v.Add() // i know v.(*mystruct).Add() will solve problem. but is that really only solution?
}

https://go.dev/play/p/vme7Zuw-raB

Solution

but is that really only solution?

Yes. Or wait for Go 1.18 and wrap sync.Map in a generic container.

Answered By – Volker

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.