The difference between make and new in Go

Source: Internet
Author: User

Reference Tutorial:
Http://www.flysnow.org/2017/03/26/go-in-action-go-type.html
Http://www.flysnow.org/2017/10/23/go-new-vs-make.html

1 Types of variables

To understand the difference between make and new, the reference type and value type are the first to be understood.

1.1 Value types

The built-in raw data type in Golang is a value type. such as int, float, string, bool. Value types are immutable, so manipulating them typically returns a newly created value. When you pass these values to a function, you are actually creating a copy of the value. This is the same thing in Python. A copy is passed to the function as a parameter.

func main(){  s := "a"  modify(s)  fmt.Println(s)}func modify(s string)string{  s = "888888888"}

Because modifying a value type produces a copy of it, the value type is safe in multiple threads.

1.2 Reference types

Slices, maps, interfaces, function types, and Chan are all reference types. Modification of a reference type can affect any variable that is referenced to it.

Reference types can be referenced because we are creating a variable of reference type, which is actually a header value, and the header value contains a pointer to the underlying data structure, and when the reference type is passed in the function, a copy of the header value is passed, and the underlying structure it points to is not copied and passed. This is also why reference type delivery is efficient.

func main(){  ages := map[string]int{"s":12}  modify(ages)  fmt.Println(ages)}func modify(m map[string]int){  m["s"] = 777}

The modification of the function modify will affect the value of the ages.

1.3 Structure Type

Declare a variable of struct type with the var keyword.

type person struct{  age int  name string}// 声明var p person

This method of VAR declaration initializes the data types in the struct person by default, that is, the 0 value of their type is used.
Function arguments are value-passing, so it is no exception to structs that the struct passes itself and copies of the values inside it.

type Person struct {    age int    name string}func modify(p Person){    p.age  = 100000000000}func main(){    jim := Person{10,"jim"}    fmt.Println(jim)    modify(jim)    fmt.Println(jim)}

The output above is the same, so we verify that a copy of the value is passed. If the above example we want to modify the value of age can pass a pointer to the struct body.

type Person struct {    age int    name string}// 我觉得这样比较好理解,*Person 是针对结构体实例的操作。(可以想想面向对象的语言,Python / Java)func modify(p *Person){    p.age  = 100000000000}func main(){// jim 的类型是 Person    jim := Person{10,"jim"}// var jim Person = Person{10, "jim"}    fmt.Println(jim)// &jim 指向的是实例    modify(&jim)// var h *Person = &jim    fmt.Println(jim)// * 号在定义时使用,&在运算时使用。*这种类型在运算时映射的值是&}

1.4 Custom Types

type Duration int64

Go is a strongly typed language, so int64 and duration cannot be directly assigned to a value.

2 Declaration of variables

var i intvar s string

The declaration of a variable can be used in a program using the var keyword, and the value of the variable declared by VAR is their default value of 0.

type Default 0 value
Int 0
String ""
Reference type Nil

Assigns a value to a reference type.
*int, is a reference type that declares a value type int .
*iis an operation on a reference type of a value type.

func main(){  var i *int  *i = 10  fmt.Println(*i)}

Run-time paninc:runtime error:invalid memory address or nil pointer dereference
As you can see from this hint, for a variable of a reference type, we're not just declaring it, we're allocating memory space for it, or where do we put our values? This is the reason for the above error message.
The declaration of a value type is not required because it has been assigned to us by default, and the value type has a default value of 0.
To allocate memory, draw out today's new and make.

New

func main(){  var i *int  i = new(int)  *i = 10  fmt.Println(*i)}

Look at the built-in function of new

// The new built-in function allocates memory.The first argument is a type,not a value, and the value returned is a pointer to a newly allocated zero value of that type.func new(Type) *Type

New is a built-in function that allocates memory. The new parameter is a type, and the return value of new is a pointer. The pointer points to the default 0 value of the parameter.

func main(){// 这个u 是什么类型,*user, 为啥?因为new函数返回的是一个指向参数类型默认零值的指针啊。// 这种方式和上文中 u := user{}, &u 的方式实际上是一样的。    u := new(user)    u.lock.Lock()    u.name = "sssssssss"    u.lock.Unlock()    fmt.Println(u)}type user struct {    lock sync.Mutex    name string    age int}

This is new, which returns always a pointer to the type, pointing to the memory address of the allocation type.

Make

Make is also used for memory allocations, but unlike new, it is used only for chan/map and tile memory creation, and the type returned is the three types themselves, not their pointer types. Because Chan/map/slices are already reference types, it is not necessary to return their pointers.
Take a look at make documentation

The Make built-in function allocates and initializes a object of type slice, map, or Chan (only). Like new,the argument are a type, not a value. Unlike new, make's return type is the same as the type of it argument,not a pointer to it. The specification of the result depends on the type:

Slice:the size Specifies the length. The capacity of the slice is equal to its length. A second integer argument may is provided to specify a different capacity; It must is no smaller than the length, so make ([]int,0,10) allocates a slice of length 0 and capacity 10.

Map:an empty map is allocated with enough space to hold the specified number of elements. The size may be omitted,in which case a small starting size is allocated.

Channel:the Channel ' s buffer is initialized with the specified buffer capacity. If Zero, or the size is omitted, the channel is unbuffered.

func make(t Type, size ...IntegerType) Type

Make is only initialized for Slice/map/chan and allocates memory.
Like new, the first argument must be a type. Unlike new, new returns a pointer to the parameter type, which points to the default 0 value of the parameter. Make returns the same incoming type, not a pointer. Because Slice/map/chan itself is a reference type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.