版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/benben_2015/article/details/81069406
使用场景
package main
import "fmt"
func main() {
var a *string
*a ="hello world"
fmt.Println(*a)
}
执行上面的结果会报下面的错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4962da]
goroutine 1 [running]:
main.main()
D:/project/test1.go:7 +0x2a
exit status 2
出现这个问题的原因是:对于引用类型的变量,不仅要声明它,还要为它分配内存空间。而值类型的变量,默认已经帮我们分配好了。那么如何实现内存分配,就需要用到Go的两个内建函数:new()和make()。
func new(Type) *Type函数
// 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.
new(T)为每个新的类型T分配一片内存,返回一个指向类型为T的、值为零的指针,它适用于值类型:如数组和结构体。
package main
import "fmt"
func main() {
var slice1 = new([]string)
slice1 = &[]string{"hello", "world"}
fmt.Println(slice1)
}
func make(t Type, size …IntegerType) Type函数
// 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.
make(T)分配内存并初始化类型T,它只适用3种内建的引用类型:切片、map和channel。
package main
import "fmt"
func main() {
var slice1 = make([]string, 2)
slice1 = append(slice1, "hello")
slice1 = append(slice1, "world")
fmt.Println("slice1 :", slice1)
}
上面代码运行的结果为:slice1 : [ hello world]
。在元素值hello、world之前还有两个空字符串,使用append()函数是在原切片的尾部添加内容,所以make()函数初始化了一个长度为2,元素值为0的切片。
因此,当你使用append函数为make()函数创建的切片追加元素时,切片的长度应当设置为0。否则切片中就会包含空元素。
二者异同
两者都是内存的分配,但是make()只用于slice、map和channel的初始化,而new()函数适用于任何类型的内存分配。另外,make()返回的是这三个引用类型本身,而new()返回的是指向类型的指针。