请教一个直接修改map中某个值的方法
golang吧
全部回复
仅看楼主
level 1
jxdz232601 楼主
代码如下:
type Map_bytes struct {
In_bytes uint64
Out_bytes uint64
Total_bytes uint64
}
users := make(map[string]Map_bytes
_, ok := users[thiskey]
if ok == false {
var tmpu mystore.Map_bytes
tmpu.In_bytes = 0;
tmpu.Out_bytes = 0;
tmpu.Total_bytes = 0;
users1[thiskey] = tmpu
}
users[thiskey].In_bytes += In_bytes
users[thiskey].Out_bytes += Out_bytes
users[thiskey].Total_bytes += Total_bytes
上面就是大致过程,内容就是判断thiskey是否存在,不存在就初始化,存在就直接将值累加。
但是报错了:
./dpiserver.go:138:29: invalid operation: cannot index users1[thiskey] (map index expression of type Map_bytes)
./dpiserver.go:139:30: invalid operation: cannot index users1[thiskey] (map index expression of type Map_bytes)
./dpiserver.go:140:32: invalid operation: cannot index users1[thiskey] (map index expression of type Map_bytes)
不知道是什么问题,上面的操作在其他语言是常规操作,但是这里报错了,是我语法有问题,还是不允许这么做?
最终我用了个本办法,先将tmpu := users1[thiskey] ,再tmpu.In_bytes += In_bytes,最后将tmpu重新赋给users1[thiskey],这么做,貌似有点绕了。
2024年01月23日 09点01分 1
level 1
你判断key是否在的那里不是已经取出值了吗?(就是OK那里),直接在那个变量进行运算,然后重新赋值。优化一点就是你的map的val用指针,取出来的时候,直接在对象运算就行了[笑眼]
2024年01月23日 22点01分 2
谢了,你是6点半回的帖子?难道是加班到现在?[开心]
2024年01月24日 07点01分
@jxdz232601 睡的突然醒了瞄了眼手机,回复完继续睡了[笑眼]
2024年01月24日 11点01分
level 1
jxdz232601 楼主
感谢二楼提醒,我又去查了下资料,原来还可以将指针作为map的valuetype,具体做法如下:
申明map时,改为:
users := make(map[string]*mystore.Map_bytes)
初始化时,改为:
if ok == false {
var tmpu mystore.Map_bytes
tmpu.In_bytes = 0;
tmpu.Out_bytes = 0;
tmpu.Total_bytes = 0;
users[thiskey] = &tmpu
}
这样就能直接用下面语句直接赋值了:
users[thiskey].In_bytes += In_bytes
2024年01月24日 07点01分 3
初始化可以优化为: users1[thiskey] = &mystore.Map_bytes{In_bytes: 0, Out_bytes: 0, Total_bytes: 0}
2024年01月24日 08点01分
level 6
解决了就好
2024年01月25日 02点01分 4
1