gpt4 book ai didi

go - new 和 make 和有什么不一样?

转载 作者:IT老高 更新时间:2023-10-28 13:05:41 24 4
gpt4 key购买 nike

New 不会初始化内存,它只会将其归零。它返回一个指向新分配的零值的指针。

Make 只创建 slice 、贴图和 channel ,并返回它们已初始化。

在这种情况下,“初始化”是什么意思?new 和 make 之间还有哪些其他区别?

最佳答案

Making slices, maps and channels 中所述:

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions.
It returns a value of type T (not *T).
The memory is initialized as described in the section on initial values.

例如,对于 Slice type

make([]T, length, capacity)

produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:

make([]int, 50, 100)
new([100]int)[0:50]

所以在这里,make 创建 slice ,如果使用的类型(这里是 int,所以 '0')

您可以在 Go: why would I make() or new()? 中了解更多关于保持新和分开的需要


Dave cheney 刚刚写了一篇好文章:“Go has both make and new functions, what gives ?

Although make creates generic slice, map, and channel values, they are still just regular values; make does not return pointer values.

If new was removed in favour make, how would you construct a pointer to an initialised value ?

Using new to construct a pointer to a slice, map, or channel zero value works today and is consistent with the behaviour of new.

For the confusion they may cause, make and new are consistent;

  • make only makes slices, maps, and channels,
  • new only returns pointers to initialised memory.

关于go - new 和 make 和有什么不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25358130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com