如何通过地图指针在Go中更改/访问地图实例的值?

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

How to change/visit a map instance's value through map pointer in Go?

问题

假设我们有以下代码:

var Cache_map *map[string]int

Cache_map = new(map[string]int)

然后我们想要将键type和值1添加到Cache_map中,我们应该如何做呢?

英文:

Assume we have code:

var Cache_map *map[string]int

Cache_map = new(map[string]int)

Then we want to add key: type & value 1 into Cache_map, how shall we do?

答案1

得分: 3

var CacheMap = map[string]int{}

func main() {
CacheMap["type"] = 1
fmt.Printf("%#v\n", CacheMap)
}

英文:

No need for new, make or a pointer to map in this case. Skeleton/example:

package main

import "fmt"

var CacheMap = map[string]int{}

func main() {
        CacheMap["type"] = 1
        fmt.Printf("%#v\n", CacheMap)
}

Playground


Output:

map[string]int{"type":1}

答案2

得分: 2

如果你真的,真的需要这样做,例如,

package main

import "fmt"

func main() {
    var Cache_map *map[string]int
    Cache_map = new(map[string]int)
    *Cache_map = make(map[string]int)
    (*Cache_map)["type"] = 1
    fmt.Println(*Cache_map)
}

输出:

map[type:1]
英文:

If you really, really need to do that, for example,

package main

import "fmt"

func main() {
	var Cache_map *map[string]int
	Cache_map = new(map[string]int)
	*Cache_map = make(map[string]int)
	(*Cache_map)["type"] = 1
	fmt.Println(*Cache_map)
}

Output:

map[type:1]

huangapple
  • 本文由 发表于 2013年4月17日 16:11:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/16054855.html
匿名

发表评论

匿名网友

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

确定