Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between new and make in go language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the difference between new and make in go language". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what's the difference between new and make in the go language?"

The difference between new () and make ()

The following excerpt is from https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/07.2.md

Both allocate memory on the heap, but they behave differently and apply to different types.

New (T) allocates a piece of memory for each new type T, initializes to 0 and returns a memory address of type * T: this method returns a pointer to an address of type T with a value of 0, which applies to value types such as arrays and structures; it is equivalent to & T {}. Make (T) returns an initial value of type T, which applies only to three built-in reference types: slice, map, and channel

In other words, the new function allocates memory and the make function initializes; the following figure shows the difference:

As far as I understand it, new returns a pointer to a variable, but the pointer points to null, and you cannot manipulate the pointer directly, otherwise it will report an error unless you point the pointer to the address of a variable of that type.

Make returns a variable of this type. Take the slice variable as an example. As mentioned above, make is suitable for creating slices, map, and channel, but new can also create

Package mainimport "fmt" func main () {/ / create slices using make Return the variable itself S1: = make ([] int,5,10) fmt.Printf ("use make create slise type% T value% v\ n", S1 value S1) S1 [0] = 123s1 [4] = 321fmt.Printf ("make S1 type% T value% v\ n", S1 value 1) / / # create a slice using new, and return the pointer to the slice variable S2: = new ([] int) fmt.Printf ("use new create slise type% T value% v\ n", S2) S2) fmt.Printf ("new S2 type% T value% v\ n", * S2 type 2) / / if you want to assign a value, you need to use * dereference / / although syntax errors are not reported here. But there will be a run-time error if you try to use (* S2) [0] = 123 directly / / panic: runtime error: index out of ranges2 = & S1 / / need to point the variable pointer to the address of a variable of this type (* S2) [0] = 123 (* S2) [4] = 3211fmt.Printf ("new S2 type% T value% v\ n", s2jue S2) / / S2 modification will also affect s1fmt.Printf ("S1 type% T value% v\ n", S1 S1) M1: = make (map [string] string) M1 ["name"] = "yangyanxing" M1 ["age"] = "30" fmt.Printf ("M1 use make create type:%T value% v\ n", M1 string M1) m2: = new (map [string] string) fmt.Printf ("m2 use new create type:%T value% v\ n", m2 Panic: assignment to entry in nil mapm2 = & M1 (* m2) ["name"] = "fan" / / A modification to m2 will also affect m1fmt.Printf ("after m2 change M1 value is% v", M1)}

The output is

Use make create slise type [] int value [0 000] make S1 type [] int value [123 000321] use new create slise type * [] int value & [] new S2 type [] int value [] new S2 type * [] int value & [123 000 3211] S1 type [] int value [123 000 3211] M1 use make create type: mapstring string value map [name:yangyanxing age:30] m2 use new create type:* map [string] string value & map [after] M2 change m1 value is map [name:fan age:30]

Initialization of map

There are two initialization methods for map

Use the make function

Initialization using map directly

Package mainimport "fmt" func main () {/ / initialize mapmp2 with make: = make (map [string] string) mp2 ["name"] = "yangyanxing" mp2 ["age"] = "18" fmt.Println ("m2 address", & mp2) / / out:m2 address & map [name: yangyanxing age:18] mp3: = map [string] int {} / / there must be {} If there is no content in curly braces, it means that an empty dictionary mp3 ["yang"] = 18mp3 ["fan"] = 20fmt.Println (mp3) / / out:map [yang:18 fan:20] mp4: = map [string] int {"yang": 20, "fan": 21 is initialized / / even the last one should have a comma} fmt.Println (mp4) / / out:map [yang:20 fan:21] mp5: = map [string] int {"yang": 30} / / write on the same line without comma fmt.Println (mp5) / / out: map [yang: 30] mp6: = make (map [string] int,1) / / you can also add a capacity mp6 ["yang"] = 30fmt.Println ("mp6 lens is", len (mp6) "address:", & mp6) / / out:mp6 lens is 1 address: & Mapyang: 30] mp6 ["fan"] = 31fmt.Println ("mp6 lens is", len (mp6), "address:", & mp6) / / out:mp6 lens is 2 address: & Mapyang: 30 fan:31] / / you can also use new, but you cannot assign it directly Because at this time, it returns a null pointer / / needs to point to an address of a variable of this type before it can operate mp7: = new (mapping [string] int) fmt.Println (mp7) / / out:&map [] / / (* mp7) ["yang"] = 100 / / it will report a runtime error mp7 = & mp6//mp7 ["fan"] = 1000 / / and mp7 cannot be used directly. You need to use * dereference (* mp7) ["yang"] = 100 / / then the runtime error fmt.Println (mp7) / / out:&map [yang:100 fan:31]} will not be reported.

Initialization of slice slices

It can also be initialized through make and the slice itself

Package mainimport "fmt" func main () {/ / use make to initialize the slice. You need to pass a len length, and the capacity cap is optional / / if not, the length and capacity are the same sls1: = make ([] int,5,10) sls1 [0] = 100//append appended to the tail. Here sls1 = append (sls1200) / /. Three points, grammatical sugar in go, expand the previous slice sls1 = append (sls1, [] int {30 ^ 40}...) fmt.Println (sls1,len (sls1), cap (sls1)) / / out: [1000 00 200 30 40] 8 10sls1 = append (sls1,3,4,6) / / fmt.Println (sls1,len (sls1) will occur after exceeding the original capacity of the slice Cap (sls1)) / / out: [100000 20030 40 3 4 6] 11 20sls2: = make ([] int,3) sls2 [1] = 123fmt.Println (sls2,len (sls2), cap (sls2)) / / out: [0123 0] 3 3max / directly initialize sls3: = [] int {} sls3 = append (sls3,10,20) fmt.Println (sls3,len (sls3), cap (sls3)) / / out: [10 20] 2 2sls4: = [] int {1Q 3} sls5: = [] int {1Power2jin5Jazpac / the comma here cannot save} fmt.Println (sls4,sls5) / / out: [1 2 3] [1 25] / / create a slice using new, just like map, the pointer is returned You cannot operate on it directly / / you need to point to the address of a variable sls6: = new ([] int) fmt.Println (sls6) / / out: & [] sls6 = & sls4fmt.Println (sls6) / / out: & [1 2 3]}

Initialization of array array

Arrays cannot be initialized with make, but can be initialized with new

Package mainimport "fmt" type person struct {name stringage int} func main () {fmt.Println ("array initialization") / / declares and initializes an empty array with element values of type zero arr1: = [2] int {} fmt.Println (arr1) / / out: [0] / / write element values with arr2: = [2] int {1mer3} fmt.Println (arr2) / / out: [1 3] / / write only one Do not write the zero value arr3: = [2] int {1} fmt.Println (arr3) / / out: [10] / / arr4: = make ([2] int) / / the array cannot use makevar arr5 [2] intarr5 [0] = 100fmt.Println (arr5) / / [1000] / / do not specify the array size, use. The three-dot sign allows it to expand automatically to calculate arr6: = [...] int {2Power4 arr6,len (arr6)} fmt.Println (arr6,len (arr6)) / / out: [2 468] 4pm / use new to create an array The result is a pointer arr7: = new ([3] int) fmt.Println (arr7) / / out: & [000] / / you can directly operate on the pointer arr7 [0] = 3pm / same as using * dereference (* arr7) [1] = 4fmt.Println (arr7) / / out: & [340]}

Initialization of struct structure

Structures cannot use make, you need to use new and the structure itself

Package mainimport "fmt" type person struct {name stringage int} func main () {fmt.Println ("initialization of structure") / / use new to return the structure pointer stru1: = new (person) fmt.Println (stru1) / / out & {0}. The default is the zero value of the field / / you can directly use this pointer to manipulate variables / / as using * dereferencing stru1.name = "yangyanxing" (* stru1). Age = 18fmt.Println (stru1) * stru1) / & {yangyanxing 18} {yangyanxing 18} / / only one field is specified, and there is no default zero value specified stru2: = person {name: "fan"} fmt.Println (stru2) / / {fan 0} / / all fields can be initialized in the order that stru3: = person {age:18,name: "yang"} fmt.Println (stru3) / / {yang 18} / / is not defined. The value of the element must be fully written in stru4: = person {"fan", 17} fmt.Println (stru4) / / {fan 17}}

At this point, I believe you have a deeper understanding of "what is the difference between new and make in the go language?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report