Go 中什么时候应该使用 new ?
在原始语言结构中使用似乎毫无意义,因为您无法指定任何类型的值
func main() {
y := new([]float)
fmt.Printf("Len = %d", len(*y) ) // => Len = 0
}
对于结构来说它更有意义,但是说 y := new 有什么区别(my_stuct) 和看似更简洁的 y := &my_struct
?
由于您创建的任何内容都基于这些原语,因此它们将被初始化为所述零值。那么有什么意义呢?你什么时候想使用new()
?
很抱歉这个非常初学者的问题,但文档并不总是那么清晰。
It seems pointless to be used in primitive language constructs, as you can't specify any sort of values
func main() {
y := new([]float)
fmt.Printf("Len = %d", len(*y) ) // => Len = 0
}
For stucts it makes a bit more sense, but what's the difference between saying y := new(my_stuct)
and the seemingly more concise y := &my_struct
?
And since anything you create is based on those primitives, they will be initialized to the said zero values. So what's the point? When would you ever want to use new()
?
Sorry for the very-beginner question, but the documentation isn't always that clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将
new
用于切片和映射,如代码示例中所示,但必须使用make
命令:make([]float, 100)
new(MyStruct)
和 < code>&MyStruct{} 做同样的事情,因为如果你使用 & 获取值的地址,Go 会在堆上分配值。有时,代码只是以一种或另一种风格更好地表达其意图。Go 没有对构造函数的内置支持,因此通常您会将对 new 的调用包装到函数中,例如 NewMyStruct() ,它会执行所有必要的初始化。它还可以初始化私有字段或将结构隐藏在接口后面,以防止对象的用户直接弄乱其内部结构。当您在添加/删除/重命名/重新排序字段时不需要更改其所有用户时,以这种方式发展结构的结构也更容易。
You can't use
new
for slices and maps, as in your code example, but instead you must use themake
command:make([]float, 100)
Both
new(MyStruct)
and&MyStruct{}
do to the same thing, because Go will allocate values on the heap if you get their address with &. Sometimes the code just expresses it intent better in one style or the other.Go does not have built-in support for constructors, so usually you would wrap the call to
new
into a function, for exampleNewMyStruct()
which does all the necessary initialization. It also makes it possible to initialize private fields or hide the struct behind an interface, to prevent users of the object from directly messing with its internals. Also evolving the structure of the struct is easier that way, when you don't need to change all of its users when adding/removing/renaming/reordering fields.make
仅适用于映射、切片和通道,而像type{}
这样的复合文字仅适用于结构、数组、切片和映射。对于其他类型,您必须使用 new 来获取指向新分配实例的指针(如果您不想使用更长的 var v T; f(&v ))。我想如果你想初始化一个结构体,这很有用:
make
does only work for maps, slices and channels and composite literals liketype{}
work only for structs, arrays, slices, and maps. For other types, you'll have to usenew
to get a pointer to a newly allocated instance (if you don't want to use a longervar v T; f(&v)
).I guess this is useful if you want to initialize a struct: