new 和 make 是两个内置函数,主要用来创建并分配类型的内存。在我们定义变量的时候,可能会觉得有点迷惑,不知道应该使用哪个函数来声明变量,其实他们的规则很简单,
new 只分配内存,
make 只能用于 slice、map 和 channel 的初始化,
下面我们就来具体介绍一下:
在go语言中,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
var sum *int
sum = new(int) //分配空间
*sum = 98
fmt.println(*sum)
type student struct {
name string
age int
}
var s *student
s = new(student) //分配空间
s.name ="dequan"
fmt.println(s)
panic: runtime error: invalid memory address or nil pointer dereference
[signal sigsegv: segmentation violation code=0x1 addr=0x0 pc=0x80bd277]
goroutine 1 [running]:
// the make built-in function allocates and initializes an object of type
// slice, map, or chan (only). like new, the first argument is a type, not a
// value. unlike new, make's return type is the same as the type of its
// 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 be provided to
// specify a different capacity; it must be 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 函数只用于 map,slice 和 channel,并且不返回指针。如果想要获得一个显式的指针,可以使用 new 函数进行分配,或者显式地使用一个变量的地址。
go语言中的 new 和 make 主要区别如下:
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论