dushaoshuai / dushaoshuai.github.io

0 stars 0 forks source link

Go: new 和 make 的区别 #115

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago
new make
first argument Type Type
value returned *Type Type
Type any type slice, map, or chan
allocates memory
initializes object ×
package golang_test

func Example_new_a_map() {
    m := new(map[string]int)
    (*m)["a"] = 'a'

    // $ go test -run Example_new_a_map
    // --- FAIL: Example_new_a_map (0.00s)
    // panic: assignment to entry in nil map [recovered]
    //        panic: assignment to entry in nil map
}