Go 语言 中 new 和 make 是两个内置 函数,主要用来创建并分配内存。Golang 中的 new 与 make 的区别是 new 只分配内存,而 make 只能用于 slice、map 和 channel 的初始化。
make 只能用来分配及初始化类型为 slice、map、chan 的数据,而 new 可以分配任意类型的数据。
new 分配返回的是指针,即类型 *Type。make 返回引用,即 Type。
new 分配的空间被清零。make 分配空间后,会进行初始化。
func new(Type) *Type
new 函数只接受一个参数,这个参数是一个 Golang 的 数据类型,并且返回一个指向该类型内存地址的指针。同时 new 函数会把分配的内存置为零,也就是类型的零值。
func make(t Type, size ...IntegerType) Type
make 也是用于内存分配的,make 函数的 t 参数必须是 chan(通道)、map(字典)、slice(切片)中的一个。
make 和 new 不同,它只用于 chan、map 以及 slice 的内存创建,而且它返回的类型就是这三个类型本身,而不是他们的指针类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了。
使用 new 为 int 类型的数据,分配空间
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 new 为 int 类型的数据,分配空间
var num *int
num = new(int)
*num = 1024
fmt.Println("Num =", *num, "Addr =", num)
}
程序运行后,控制台输出如下:
首先,我们定义了一个 int指针类型的 变量 num,接着,我们使用 new 为变量 num 分配内存,接着为 num 变量赋值为 1024。
最后,我们使用 print 打印 num 的值和 num 变量的地址。
使用 new 为自定义类型,分配空间
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 new 为自定义类型,分配空间
var p *Person
p = new(Person)
p.Name = "HaiCoder"
p.Age = 18
fmt.Println("Person =", p)
}
程序运行后,控制台输出如下:
首先,我们定义了一个结构体 Person,该结构体有两个字段,一个是 string 类型的 Name,另一个是 int 类型的 Age。
接着,我们在 main 函数里面定义一个 Person 指针类型的变量 p,并使用 new 为其分配内存,并为结构体变量的字段赋值。最后,我们打印结构体变量 p 。
使用 make 为切片分配空间
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 make 为切片分配空间
var nums []int
nums = make([]int, 0, 10)
nums = append(nums, 1)
nums = append(nums, 2)
nums = append(nums, 3)
fmt.Println("Nums =", nums)
}
程序运行后,控制台输出如下:
首先,我们定义了一个 int 切片类型的变量 nums,接着使用 make 为其分配内存,并使用 append 为切片变量添加数据。
最后,我们使用 print 打印打印切片变量 nums 的值。
使用 make 为map分配空间
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 make 为map分配空间
var mNum = make(map[int]string, 10)
mNum[0] = "Hello"
mNum[1] = "HaiCoder"
mNum[2] = "嗨客网"
fmt.Println("mNum =", mNum)
}
程序运行后,控制台输出如下:
首先,我们定义了一个 map 类型的变量 mNum,接着使用 make 为其分配内存。
make 只能用来分配及初始化类型为 slice、map、chan 的数据,而 new 可以分配任意类型的数据。
new 分配返回的是指针,即类型 *Type。make 返回引用,即 Type。
new 分配的空间被清零。make 分配空间后,会进行初始化。