英文:
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)
}
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论