Home >Backend Development >Golang >The difference between golang make and new

The difference between golang make and new

(*-*)浩
(*-*)浩Original
2019-12-03 11:19:533080browse

The difference between golang make and new

make, new operation

make is used for memory allocation of built-in types (map, slice and channel) . new is used for various types of memory allocation. (Recommended learning: go)

The built-in function new essentially has the same function as the function of the same name in other languages: new(T) is assigned zero value filling The memory space of type T and returns its address, which is a value of type *T.

In Go terms, it returns a pointer to a newly allocated zero value of type T. One thing is very important:

new返回指针。

The built-in function make(T, args) has different functions from new(T). make can only create slice, map and channel, and return a Type T with initial (non-zero) value, not *T. Essentially, the reason why these three types are different is that references to data structures must be initialized before use.

For example, a slice is a three-item descriptor containing a pointer to the data (internal array), length, and capacity; the slice is nil before these items are initialized. For slices, maps, and channels, make initializes the internal data structures and fills them with appropriate values.

make返回初始化后的(非零)值。

Code example:

var map1 map[string]string = make(map[string]string)
    fmt.Println(map1)
    fmt.Println(map1 == nil)

    var map2 *map[string]string = new(map[string]string)
    fmt.Println(map2)
    fmt.Println(map2 == nil)
    fmt.Println(*map2)
    fmt.Println(*map2 == nil)
    //    var map1 map[string]string
    map1["aaa"] = "AAA"
    map1["bbb"] = "BBB"
    map1["ccc"] = "CCC"
    fmt.Println(map1)
    fmt.Println(len(map1))

Output:

map[]
false
&map[]
false
map[]
true
map[bbb:BBB ccc:CCC aaa:AAA]
Success: process exited with code 0.

The above is the detailed content of The difference between golang make and new. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to design golang logNext article:How to design golang log