Go 中什么时候应该使用 new ?

发布于 2024-09-07 09:44:33 字数 359 浏览 5 评论 0原文

在原始语言结构中使用似乎毫无意义,因为您无法指定任何类型的值

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

超可爱的懒熊 2024-09-14 09:44:33

您不能将 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 the make 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 example NewMyStruct() 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.

浅浅淡淡 2024-09-14 09:44:33

make 仅适用于映射、切片和通道,而像 type{} 这样的复合文字仅适用于结构、数组、切片和映射。对于其他类型,您必须使用 new 来获取指向新分配实例的指针(如果您不想使用更长的 var v T; f(&v ))。

我想如果你想初始化一个结构体,这很有用:

typedef foo struct {
    bar *int
}
v := foo{bar: new(int)}

make does only work for maps, slices and channels and composite literals like type{} work only for structs, arrays, slices, and maps. For other types, you'll have to use new to get a pointer to a newly allocated instance (if you don't want to use a longer var v T; f(&v)).

I guess this is useful if you want to initialize a struct:

typedef foo struct {
    bar *int
}
v := foo{bar: new(int)}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文