Home > Net >  golang - struct in sync map access
golang - struct in sync map access

Time:02-17

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

CodePudding user response:

but is that really only solution?

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

  •  Tags:  
  • go
  • Related