new 函数
咱们间接申明一个指针类型的变量 p ,而后对扭转量的值进行批改,为“微客鸟窝”:
func main() { var p *string *p = "微客鸟窝" fmt.Println(*p)}
程序运行,会报错:
panic: runtime error: invalid memory address or nil pointer dereference
这是因为指针类型的变量如果没有分配内存,默认值是零值 nil
。它没有指向的内存,所以无奈应用。
如果要应用,给它调配一块内存就能够了,能够应用 new函数:
func main() { var p *string p = new(string) //new函数进行内存调配 *p = "微客鸟窝" fmt.Println(*p)}
下面示例便能够失常运行,内置函数 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
作用:
- 依据传入的类型申请一块内存,而后返回指向这块内存的指针
- 指针指向的数据就是该类型的零值
- 比方传入的类型是 string,那么返回的就是 string 指针,这个 string 指针指向的数据就是空字符串
变量初始化
申明完变量,对变量进行赋值,就是所谓的初始化。
string 类型变量初始化:
var s string = "微客鸟窝"s1 := "微客鸟窝"
指针变量初始化
咱们能够定义一个函数来进行初始化指针变量
package mainimport "fmt"func main() { pp:=NewPerson("微客鸟窝",18) fmt.Println(pp) //&{微客鸟窝 18}}type person struct { name string age int}func NewPerson(name string,age int) *person{ p := new(person) p.name = name p.age = age return p}
make 函数
上文咱们曾经理解到,在应用 make 函数创立 map 的时候,其实调用的是 makemap 函数:
// makemap implements Go map creation for make(map[k]v, hint).func makemap(t *maptype, hint int, h *hmap) *hmap{ //省略无关代码}
makemap 函数返回的是 *hmap 类型,而 hmap 是一个构造体,它的定义如下:
// A header for a Go map.type hmap struct { // Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go. // Make sure this stays in sync with the compiler's definition. count int // # live cells == size of map. Must be first (used by len() builtin) flags uint8 B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items) noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details hash0 uint32 // hash seed buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated) extra *mapextra // optional fields}
能够看到, map 关键字其实非常复杂,它蕴含 map 的大小 count、存储桶 buckets 等。要想应用 hmap ,只是通过简略的 new 函数来返回一个 *hmap 就能够实现的,还须要对其进行初始化,这就是 make 所施展的作用:
m := make(map[string]int,10)
咱们发现 make 函数跟下面的自定义的 NewPerson 函数很像,其实 make 函数就是 map 类型的工厂函数,它能够依据传递给它的键值对类型,创立不同类型的 map ,同时能够初始化 map 的大小。
make 函数不只是 map 类型的工厂函数,还是 chan、slice 的工厂函数。它同时能够用于 slice、chan 和 map 这三种类型的初始化。
- new 函数只用于分配内存,且把内存清零,不太罕用。
- make 函数只用于 slice、chan 和 map 这三种内置类型的创立和初始化,因为这三种类型构造比较复杂,比方 slice 要提前初始化好外部元素的类型,slice 的长度和容量等。