Table of Contents
new
make
Summary:
Home Backend Development Golang What is the difference between make and new in go language?

What is the difference between make and new in go language?

Dec 09, 2020 am 10:59 AM
go language make new

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.

What is the difference between make and new in go language?

#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)
Copy after login

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)
Copy after login

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)
Copy after login

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
Copy after login

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) //{}
Copy after login

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}
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login

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)
Copy after login

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"}
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

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, ...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

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

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

How to solve the problem that custom structure labels in Goland do not take effect? How to solve the problem that custom structure labels in Goland do not take effect? Apr 02, 2025 pm 12:51 PM

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...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

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...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

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 do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Why do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Apr 02, 2025 pm 04:09 PM

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...

See all articles