Go语言:new还是make?到底该如何选择?

1,121 阅读3分钟

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 main

import "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 的长度和容量等。