Golang new和make

简述

new() 和 make() 都是用于动态分配内存的内建函数

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
  1. 初始化指定类型分配内存空间,并返回该类型的零值
  2. 返回的值为指针类型
  3. 适用于所有的数据类型(除了channel、map)
    实例:
package main

import "fmt"

type People struct {
	name string
	age  int
}

func main() {
	t_int := new(int)
	fmt.Println("t_int初始化值为:", *t_int)

	people := new(People)
	people.name = "hh"
	people.age = 18
	fmt.Println(people)
}

// 结果
t_int初始化值为: 0
&{hh 18}

make()函数

make()只能用于对channelslicemap类型对初始化
官方定义:

//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.

func make(t Type, size ...IntegerType) Type
  1. make 是为channelslicemap类型分配内存和初始化的
  2. make返回的是指定类型的类型,因为channelslicemap本身就是引用类型
// slice
a := make([]int, 2, 10)

// map
b := make(map[string]int)

// channel
c := make(chan int, 10)

总结

new基本可以为所有类型分配内存和初始化
make函数只能为channelslicemap进行初始化,并返回指定类型的类型;但不是置为零值
new不常用;channelslicemap的初始化必须使用make

posted @ 2022-01-27 16:26  焦耳|程  阅读(37)  评论(0编辑  收藏  举报