The difference between new and make in Go language

1. new can be of any type, and returns a pointer: *T, only allocates memory, does not initialize memory, just sets it to zero
2. make can only be used for map, slice, chan, and returns an initialized (not set) zero), a value of type T

Example:

var map1 = new(map[string]string)
(*map1)["china"] = "中国"    // 此处会报错:panic: assignment to entry in nil map。
                                               //  因为map零值为nil,不能向为nil的map中增加数据

var map2 = make(map[string]string)
map2["china"] = "中国"   // 因为make返回一个已经初始化的map,可以直接向其中增加数据 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324941850&siteId=291194637