golang sync.map key不可以是指针

44 篇文章 0 订阅
11 篇文章 0 订阅
本文通过两个示例展示了 Go 语言中 sync.Map 的使用,探讨了为何在第一个例子中无法正确获取存储值的问题。指出在没有自定义哈希和比较函数的情况下,sync.Map 的工作原理可能导致查找失败。同时,强调了正确使用 sync.Map 的关键点。
摘要由CSDN通过智能技术生成
package main

import (
	"fmt"
	"sync"
)

type Key struct {
	A int64
	B int64
}

func main() {
	timers := new(sync.Map)
	timers.Store(&Key{
		A: 10,
		B: 2,
	}, "test1")

	if a, ok := timers.Load(&Key{
		A: 10,
		B: 2,
	}); ok {
		v := a.(string)
		fmt.Println(v)
	}
}

运行未打印出"test1"


Process finished with the exit code 0

运行如下代码:

package main

import (
	"fmt"
	"sync"
)

type Key struct {
	A int64
	B int64
}

func main() {
	timers := new(sync.Map)
	timers.Store(Key{
		A: 10,
		B: 2,
	}, "test1")

	if a, ok := timers.Load(Key{
		A: 10,
		B: 2,
	}); ok {
		v := a.(string)
		fmt.Println(v)
	}
}

结果:

test1

Process finished with the exit code 0

此哈希表并没有提供对应的哈希函数和比较函数,不太好用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值