What is the difference between make and new in go language?
Difference: In the Go language, make and new both allocate memory (on the heap), but make is only used for initialization of slice, map and channel (non-zero values); while new is used for types Memory is allocated, and memory is set to zero. make returns the reference type itself; new returns a pointer to the type.
#The operating environment of this article: windows10 system, GO 1.11.2, thinkpad t480 computer.
Related recommendations: "go tutorial"
In the Go language, new and make are both primitives used for memory allocation (allocation primitives). Simply put, new only allocates memory, and make is used for initialization of slice, map, and channel.
new
The new(T) function is a built-in function that allocates memory.
We all know that for an existing variable, its pointer can be assigned.
Example
var p int var v *int v = &p *v = 11 fmt.Println(*v)
So, what happens if it is not a variable that already exists? Can it be assigned a value directly?
Example
var v *int *v = 8 fmt.Println(*v)
The result will be the following error
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc =0x48df66]
How to solve it? This can be solved by Go providing new to initialize an address.
var v *int v = new(int) *v = 8 fmt.Println(*v)
Then let’s analyze it
var v *int fmt.Println(*v) fmt.Println(v) //<nil> v = new(int) fmt.Println(*v)// fmt.Println(v)//0xc00004c088
We can see that when a pointer variable is initialized, its value is nil, and the value of nil cannot be assigned directly. Through new, it returns a pointer to a newly allocated type int. The pointer value is 0xc00004c088. The value of the content pointed to by this pointer is zero value.
At the same time, it should be noted that the zero value of different pointer types is different.
Example
type Name struct { P string } var av *[5]int var iv *int var sv *string var tv *Name av = new([5]int) fmt.Println(*av) //[0 0 0 0 0 0] iv = new(int) fmt.Println(*iv) // 0 sv = new(string) fmt.Println(*sv) // tv = new(Name) fmt.Println(*tv) //{}
The above describes how to assign values to ordinary types after new() is processed. Here we will talk about composite types (array, slice, map, channel, etc.), new( ), how to assign value after processing.
Array example
var a [5]int fmt.Printf("a: %p %#v \n", &a, a)//a: 0xc04200a180 [5]int{0, 0, 0, 0, 0} av := new([5]int) fmt.Printf("av: %p %#v \n", &av, av)//av: 0xc000074018 &[5]int{0, 0, 0, 0, 0} (*av)[1] = 8 fmt.Printf("av: %p %#v \n", &av, av)//av: 0xc000006028 &[5]int{0, 8, 0, 0, 0}
silce example
var a *[]int fmt.Printf("a: %p %#v \n", &a, a) //a: 0xc042004028 (*[]int)(nil) av := new([]int) fmt.Printf("av: %p %#v \n", &av, av) //av: 0xc000074018 &[]int(nil) (*av)[0] = 8 fmt.Printf("av: %p %#v \n", &av, av) //panic: runtime error: index out of range
map example
var m map[string]string fmt.Printf("m: %p %#v \n", &m, m)//m: 0xc042068018 map[string]string(nil) mv := new(map[string]string) fmt.Printf("mv: %p %#v \n", &mv, mv)//mv: 0xc000006028 &map[string]string(nil) (*mv)["a"] = "a" fmt.Printf("mv: %p %#v \n", &mv, mv)//这里会报错panic: assignment to entry in nil map
channel example
cv := new(chan string) fmt.Printf("cv: %p %#v \n", &cv, cv)//cv: 0xc000074018 (*chan string)(0xc000074020) //cv <- "good" //会报 invalid operation: cv <- "good" (send to non-chan type *chan string)
Through the above example we see that the array passes new processing, the array av is initialized with zero value. Although the array is a composite type, it is not a reference type. Other silce, map, and channel types are also reference types. Go will initialize the reference type to nil, and nil cannot be assigned directly. And you cannot use new to allocate memory. Cannot be assigned directly. So what would it be like to use the make function?
make
Example
av := make([]int, 5) fmt.Printf("av: %p %#v \n", &av, av) //av: 0xc000046400 []int{0, 0, 0, 0, 0} av[0] = 1 fmt.Printf("av: %p %#v \n", &av, av) //av: 0xc000046400 []int{1, 0, 0, 0, 0} mv := make(map[string]string) fmt.Printf("mv: %p %#v \n", &mv, mv) //mv: 0xc000074020 map[string]string{} mv["m"] = "m" fmt.Printf("mv: %p %#v \n", &mv, mv) //mv: 0xc000074020 map[string]string{"m":"m"} chv := make(chan string) fmt.Printf("chv: %p %#v \n", &chv, chv) //chv: 0xc000074028 (chan string)(0xc00003e060) go func(message string) { chv <- message // 存消息 }("Ping!") fmt.Println(<-chv) // 取消息 //"Ping!" close(chv)
make can not only open up a memory, but also initialize its zero value for the type of this memory.
It can also be used in conjunction with new
Example
var mv *map[string]string fmt.Printf("mv: %p %#v \n", &mv, mv)//mv: 0xc042004028 (*map[string]string)(nil) mv = new(map[string]string) fmt.Printf("mv: %p %#v \n", &mv, mv)//mv: 0xc000006028 &map[string]string(nil) (*mv) = make(map[string]string) (*mv)["a"] = "a" fmt.Printf("mv: %p %#v \n", &mv, mv)//mv: 0xc042004028 &map[string]string{"a":"a"}
Allocate a memory to the pointer variable mv through new and assign it a memory address. Map is a reference type, and its zero value is nil. Use make to initialize map, and then the variable can be assigned a value to the pointer variable mv using *
.
Summary:
- make and new are both built-in functions used by golang to allocate memory, and allocate memory on the heap. make allocates memory and initializes memory. new only clears the memory and does not initialize the memory.
- make returns the reference type itself; while new returns a pointer to the type.
- make can only be used to allocate and initialize data of types slice, map, and channel; new can allocate any type of data.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of What is the difference between make and new in go language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Regarding the problem of custom structure tags in Goland When using Goland for Go language development, you often encounter some configuration problems. One of them is...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Why does map iteration in Go cause all values to become the last element? In Go language, when faced with some interview questions, you often encounter maps...
