Go语言中new和make关键字有哪些区别

其他教程   发布日期:2024年04月24日   浏览次数:363

本篇内容介绍了“Go语言中new和make关键字有哪些区别”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

new

new 是一个内置函数,它会分配一段内存,并返回指向该内存的指针。

其函数签名如下:

源码

  1. // The new built-in function allocates memory. The first argument is a type,
  2. // not a value, and the value returned is a pointer to a newly
  3. // allocated zero value of that type.
  4. func new(Type) *Type

从上面的代码可以看出,new 函数只接受一个参数,这个参数是一个类型,并且返回一个指向该类型内存地址的指针。

同时 new 函数会把分配的内存置为零,也就是类型的零值。

使用

使用 new 函数为变量分配内存空间:

  1. p1 := new(int)
  2. fmt.Printf("p1 --> %#v
  3. ", p1) //(*int)(0xc42000e250)
  4. fmt.Printf("p1 point to --> %#v
  5. ", *p1) //0
  6. var p2 *int
  7. i := 0
  8. p2 = &i
  9. fmt.Printf("p2 --> %#v
  10. ", p2) //(*int)(0xc42000e278)
  11. fmt.Printf("p2 point to --> %#v
  12. ", *p2) //0

上面的代码是等价的,

  1. new(int)
将分配的空间初始化为 int 的零值,也就是 0,并返回 int 的指针,这和直接声明指针并初始化的效果是相同的。

当然,new 函数不仅能够为系统默认的数据类型分配空间,自定义类型也可以使用 new 函数来分配空间,如下所示:

  1. type Student struct {
  2. name string
  3. age int
  4. }
  5. var s *Student
  6. s = new(Student) //分配空间
  7. s.name = "zhangsan"
  8. fmt.Println(s)

这就是 new 函数,它返回的永远是类型的指针,指针指向分配类型的内存地址。需要注意的是,new 函数只会分配内存空间,但并不会初始化该内存空间。

make

make 也是用于内存分配的,但是和 new 不同,它只用于 slice、map 和 chan 的内存创建,而且它返回的类型就是这三个类型本身,而不是他们的指针类型。因为这三种类型本身就是引用类型,所以就没有必要返回他们的指针了。

其函数签名如下:

源码

  1. // The make built-in function allocates and initializes an object of type
  2. // slice, map, or chan (only). Like new, the first argument is a type, not a
  3. // value. Unlike new, make's return type is the same as the type of its
  4. // argument, not a pointer to it. The specification of the result depends on
  5. // the type:
  6. // Slice: The size specifies the length. The capacity of the slice is
  7. // equal to its length. A second integer argument may be provided to
  8. // specify a different capacity; it must be no smaller than the
  9. // length, so make([]int, 0, 10) allocates a slice of length 0 and
  10. // capacity 10.
  11. // Map: An empty map is allocated with enough space to hold the
  12. // specified number of elements. The size may be omitted, in which case
  13. // a small starting size is allocated.
  14. // Channel: The channel's buffer is initialized with the specified
  15. // buffer capacity. If zero, or the size is omitted, the channel is
  16. // unbuffered.
  17. func make(t Type, size ...IntegerType) Type

通过上面的代码可以看出 make 函数的

  1. t
参数必须是 slice、map 和 chan 中的一个,并且返回值也是类型本身。

使用

下面用 slice 来举一个例子:

  1. var s1 []int
  2. if s1 == nil {
  3. fmt.Printf("s1 is nil --> %#v
  4. ", s1) // []int(nil)
  5. }
  6. s2 := make([]int, 3)
  7. if s2 == nil {
  8. fmt.Printf("s2 is nil --> %#v
  9. ", s2)
  10. } else {
  11. fmt.Printf("s2 is not nill --> %#v
  12. ", s2)// []int{0, 0, 0}
  13. }

slice 的零值是

  1. nil
,但使用 make 初始化之后,slice 内容被类型 int 的零值填充,如:
  1. []int{0, 0, 0}

map 和 chan 也是类似的,就不多说了。

以上就是Go语言中new和make关键字有哪些区别的详细内容,更多关于Go语言中new和make关键字有哪些区别的资料请关注九品源码其它相关文章!