Go language learning: new and make

new and make are used to allocate memory

	var a int
	fmt.Println(a)

	var b string
	b = "927"
	fmt.Println(b)
	//输出
	//0
	//927

Use basic types of system will default memory allocation basic types have a default value at the time of creation

	var a *string
	*a = "927"
	fmt.Println(a)
	
	var m map[string]int
	m["id"] = 927
	fmt.Println(m)
	//panic: runtime error: invalid memory address or nil pointer dereference
	//[signal 0xc0000005 code=0x0 addr=0x0 pc=0x49dd4a]
	//
	//goroutine 1 [running]:
	//main.main()
	//	E:/goworkspace/github.com/godemo/01/main.go:8 +0x2a

If the pointer and reference types not allocated memory when the
panic: runtime error: invalid memory address or nil pointer dereference

new

Function is obtained using the new type of a pointer, the value of the default value of this type.
new new (the Type)
new new function with less

	var a = new(int)
	fmt.Println(*a)
	*a = 927
	fmt.Println(*a)
	//输出
	//0
	//927
make

also make for memory allocation
for the slice, map memory and creating chan
slice, map and chan reference type is present it is unnecessary to return a pointer to
make (tyep, size)

	var m = make(map[string]int,20)
	m["id"] = 927
	fmt.Println(m)
	//输出
	//map[id:927]
Make the difference between new and

1.new less used
2.make only for slice, map memory allocation and chan
3.new returns a pointer type, make this type of return is itself

Published 11 original articles · won praise 1 · views 1254

Guess you like

Origin blog.csdn.net/ZHOUAXING/article/details/105044524