golang – struct in sync map access

huangapple go评论82阅读模式
英文:

golang - struct in sync map access

问题

我正在尝试加载在sync.Map中任意定义的结构类型数据。有没有一种方便的方式通过定义(类似于泛型,sync.Map[struct]{})来访问map类型?

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() // 我知道v.(*mystruct).Add()可以解决问题,但这是唯一的解决方案吗?
}

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

英文:

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

答案1

得分: 4

是的。或者等待Go 1.18,并在通用容器中包装sync.Map。

英文:

> but is that really only solution?

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

huangapple
  • 本文由 发表于 2022年2月17日 15:54:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/71154279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定