Why can't I initialize a map with new() in Go?

后端 未结 2 1843
既然无缘
既然无缘 2021-01-27 07:31
package main

import \"fmt\"

func main() {
    p := new(map[string]int)
    m := make(map[string]int)
    m[\"in m\"] = 2
    (*p)[\"in p\"] = 1
    fmt.Println(m)
             


        
2条回答
  •  借酒劲吻你
    2021-01-27 08:13

    This is not directly an issue with new keyword. You would get the same behavior, if you did not initialize your map, when declaring it with var keyword, for example:

    var a map[string]int
    a["z"] = 10
    

    The way to fix this is to initialize the map:

    var a map[string]int
    a = map[string]int{}
    a["z"] = 10
    

    And it works the same way, with new keyword:

    p := new(map[string]int)
    *p = map[string]int{}
    (*p)["in p"] = 1 
    

    The reason make(map[string]int) does what you expect is that the map is declared and initialized.

    Go Playground

提交回复
热议问题