what does make and new actually do?

huangapple go评论68阅读模式
英文:

what does make and new actually do?

问题

在Go语言中,如果我想创建一个类型为T的对象,可以尝试以下几种方式:

t := T{} // t是在当前堆栈中创建的实际对象
p := &T{} // p是指向在当前堆栈中创建的实际对象的指针
p := make(T) // p是指向在堆中创建的实际对象的指针
p := new(T) // p是指向在堆中创建的实际对象的指针

我想知道我的注释是否正确?

英文:

In Go, if I want to create an Object of T, I can try these ways:

t := T{} // t is the actual object created in the current stack
p := &T{} // p is a pointer points to the actual object which is created in the current stack
p := make(T) // p is a pointer points to the actual object which is created in the heap
p := new(T) // p is a pointer points to the actual object which is created in the heap

I'm wondering whether my comments are correct or not?

答案1

得分: 8

我在我的博客上写了关于这个的文章。

http://dave.cheney.net/2014/08/17/go-has-both-make-and-new-functions-what-gives

英文:

I've written about this on my blog.

http://dave.cheney.net/2014/08/17/go-has-both-make-and-new-functions-what-gives

答案2

得分: 3

不完全正确,对象是分配在堆栈还是堆上取决于逃逸分析,而不是实例化对象时使用的特定符号。Dave也写了一些关于这个问题的东西。

英文:

> t := T{} // t is the actual object created in the current stack
>
> p := &T{} // p is a pointer points to the actual object which is created in the current stack
>
> p := make(T) // p is a pointer points to the actual object which is created in the heap
>
> p := new(T) // p is a pointer points to the actual object which is created in the heap
>
> I'm wondering whether my comments are correct or not?

Not quite, whether an object is allocated on the stack or the heap depends on escape analysis not the particular notation used to instantiate the object and actually Dave wrote something about that also.

答案3

得分: 1

观察结果的类型是有指导意义的。

  • make(T, ...) 返回类型 Tmake 只能用于一些内置类型(切片、映射、通道)。它基本上是这些类型的“构造函数”。
  • new(T) 返回类型 *T。它适用于所有类型,并且对所有类型都执行相同的操作——返回一个类型为 T 的新实例的指针,其零值为默认值。
英文:

Looking at the type of the result is instructive.

  • make(T, ...) returns type T. make can only be used for a few built-in types (slice, map, channel). It is basically a "constructor" for those types.
  • new(T) returns type *T. It works for all types and does the same thing for all types -- it returns a pointer to a new instance of type T with zero value.

huangapple
  • 本文由 发表于 2014年9月9日 18:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/25742162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定