介绍文档用了很多段落来解释new()和make()之间的区别,但实际上,您可以在局部范围内创建对象并返回它们。
为什么要使用这对分配器?
介绍文档用了很多段落来解释new()和make()之间的区别,但实际上,您可以在局部范围内创建对象并返回它们。
为什么要使用这对分配器?
当前回答
make function allocates and initializes an object of type slice, map, or chan only. Like new, the first argument is a type. But, it can also take a second argument, the size. Unlike new, make’s return type is the same as the type of its argument, not a pointer to it. And the allocated value is initialized (not set to zero value like in new). The reason is that slice, map and chan are data structures. They need to be initialized, otherwise they won't be usable. This is the reason new() and make() need to be different.
下面是Effective Go的例子:
p *[]int = new([]int) // *p = nil, which makes p useless
v []int = make([]int, 100) // creates v structure that has pointer to an array, length field, and capacity field. So, v is immediately usable
其他回答
new(T):它返回一个指向类型T的指针,一个类型为*T的值,它分配并归零内存。new(T)等价于&T{}。
make(T):返回类型为T的初始化值,分配并初始化内存。它用于切片,映射和通道。
已经有很多很好的答案,但是让我解释一下new()和make()作为单独的分配器的必要性。
new(T)分配给定类型T的未初始化的零内存,并返回指向该内存的指针,以便它可以使用。归零仅仅意味着分配的内存中给定类型的值为零。某些go类型的零值为- Int - 0 Bool - false Float - 0 字符串- "" struct -每个成员的零值
Problem with new() arises when it needs to handle three other composite types - chan, slice and map. These three types are special in essence that their underlying type is not just an another type but rather a state that needs to be initialized. For example , the underlying state of a slice consists of a pointer to the first element of internal array storage, a length that determines number of elements that can be accessed and a capacity that increases as the number of elements grow. new() certainly cannot handle allocation of such types due to their need for extra initialization step, that is where make() come into play.
make(T, args)是专门为chan, slice和map类型创建的。它不仅分配chan、slice和map的内部存储类型,而且还初始化它们的底层状态,使它们可以使用。例如,对于片,它分配内部数组存储,设置指针指向该数组中的第一个元素,并设置长度和容量值。
你能用它做的事情用其他方法做不到:
创建通道 创建一个预分配空间的映射 创建一个预先分配空间的切片,或者使用len != cap
要证明新的合理性有点难。它简化的主要事情是创建指向非复合类型的指针。 下面两个函数是等价的。一个更简洁一点:
func newInt1() *int { return new(int) }
func newInt2() *int {
var i int
return &i
}
new()和make()的区别:
new(T)为一个类型为T的新项分配零存储,并返回它的地址,一个类型为*T的值:它返回一个指向新分配的类型为T的零值的指针,准备使用;它适用于数组和结构等值类型;它是 等价于&T{} make(T)返回一个初始化的T类型值;它只适用于3种内置的引用类型:切片、映射和通道。
换句话说,新的分配;使初始化;
var p *[]int = new([]int)
or
// *p == nil; with len and cap 0
p := new([]int)
这很少有用。
p := make([]int, 0)
我们的切片已经初始化,但这里指向一个空数组。
这两种说法都不是很有用,下面是:
var v []int = make([]int, 10, 50)
// Or
v := make([]int, 10, 50)
这将分配一个50个整型数组,然后创建一个长度为10,容量为50的切片v,指向数组的前10个元素。
找出make()和new()的一些规则:
对于切片、映射和通道:使用make 对于数组、结构和所有值类型:使用new
package main
type Foo map[string]string
type Bar struct {
s string
i int
}
func main() {
// OK:
y := new(Bar)
(*y).s = "hello"
(*y).i = 1
// NOT OK:
z := make(Bar) // compile error: cannot make type Bar
z.s = "hello"
z.i = 1
// OK:
x := make(Foo)
x["x"] = "goodbye"
x["y"] = "world"
// NOT OK:
u := new(Foo)
(*u)["x"] = "goodbye" // !!panic!!: runtime error:
// assignment to entry in nil map
(*u)["y"] = "world"
}
渠道:
func main() {
// OK:
ch := make(chan string)
go sendData(ch)
go getData(ch)
time.Sleep(1e9)
// NOT OK:
ch := new(chan string)
go sendData(ch) // cannot use ch (variable of type *chan string)
// as chan string value in argument to sendData
go getData(ch)
time.Sleep(1e9)
}
func sendData(ch chan string) {
ch <- "Washington"
ch <- "Tripoli"
ch <- "London"
ch <- "Beijing"
ch <- "Tokio"
}
func getData(ch chan string) {
var input string
for {
input = <-ch
fmt.Printf("%s ", input)
}
}
除了在Effective Go中解释的所有内容外,new(T)和&T{}之间的主要区别是后者显式执行堆分配。但是,应该注意的是,这取决于实现,因此可能会发生变化。
比较make和new没有什么意义,因为两者执行完全不同的功能。但这在链接的文章中有详细的解释。