golang – struct in sync map access


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 (

type mystruct struct {
    cnt int

func (m *mystruct) Add() {
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?



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.