package mainimport ("fmt")func main() {var i *int*i=10fmt.Println(*i)}输出:panic: runtime error: invalid memory address or nil pointer dereference[signal 0xc0000005 code=0x1 addr=0x0 pc=0x105b6a]goroutine 1 [running]:main.main()C:/Users/LZ.LI/Desktop/code/learn/main.go:9 +0x2a
对于引用类型的变量,我们不光要声明它,还要为它分配内容空间
正确的做法:
func main() {var i *inti=new(int)*i=10fmt.Println(*i)}
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
它只接受一个参数,这个参数是一个类型,分配好内存后,返回一个指向该类型内存地址的指针。同时请注意它同时把分配的内存置为零,也就是参数类型的零值。它返回的永远是类型的指针,指向分配类型的内存地址。
make
只用于
- chan
- map
- slice
它返回的类型就是这三个类型本身,而不是他们的指针类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了。
