简述
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
- 初始化指定类型分配内存空间,并返回该类型的零值
- 返回的值为指针类型
- 适用于所有的数据类型(除了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()函数
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
channelslicemapchannelslicemap
// slice
a := make([]int, 2, 10)
// map
b := make(map[string]int)
// channel
c := make(chan int, 10)
总结
channelslicemapchannelslicemap