英文:
Is there a difference between new() and "regular" allocation?
问题
在Go语言中,上述两段代码有明显的区别吗?
v := &Vector{} 与 v := new(Vector) 有什么不同?
英文:
In Go, is there a notable difference between the following two segments of code:
v := &Vector{}
as opposed to
v := new(Vector)
答案1
得分: 53
不. 它们返回的是相同的,
package main
import "fmt"
import "reflect"
type Vector struct {
x int
y int
}
func main() {
v := &Vector{}
x := new(Vector)
fmt.Println(reflect.TypeOf(v))
fmt.Println(reflect.TypeOf(x))
}
结果:
*main.Vector
*main.Vector
邮件列表上有一些争议,认为同时存在两者会令人困惑:
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/GDXFDJgKKSs
需要注意的一点是:
> new() 是获取指向未命名整数或其他基本类型的指针的唯一方法。你可以写成 "p := new(int)",但你不能写成 "p := &int{0}"。除此之外,这只是个人偏好。
来源: https://groups.google.com/d/msg/golang-nuts/793ZF_yeqbk/-zyUAPT-e4IJ
英文:
No. What they return is the same,
package main
import "fmt"
import "reflect"
type Vector struct {
x int
y int
}
func main() {
v := &Vector{}
x := new(Vector)
fmt.Println(reflect.TypeOf(v))
fmt.Println(reflect.TypeOf(x))
}
Result:
*main.Vector
*main.Vector
There is some contention on the mailing list that having both is confusing:
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/GDXFDJgKKSs
One thing to note:
> new() is the only way to get a pointer to an
> unnamed integer or other basic type. You can write "p := new(int)" but
> you can't write "p := &int{0}". Other than that, it's a matter of
> preference.
Source : https://groups.google.com/d/msg/golang-nuts/793ZF_yeqbk/-zyUAPT-e4IJ
答案2
得分: 25
是的,这两个代码片段之间有根本的区别。
v := &Vector{}
仅适用于Vector
是结构体类型、映射类型、数组类型或切片类型。
v := new(Vector)
适用于任何类型的Vector
。
示例:http://play.golang.org/p/nAHjL1ZEuu
英文:
Yes, there is a fundamental difference between the two code fragments.
v := &Vector{}
Works only for Vector
being a struct type, map type, array type or a slice type
v := new(Vector)
Works for Vector
of any type.
Example: http://play.golang.org/p/nAHjL1ZEuu
答案3
得分: -5
这里有一个区别:对于一个Person
结构体,从&[]*Person{}
序列化得到的JSON字符串是[]
,而从new([]*Person)
序列化得到的是null
,使用的是json.Marshal
。
在这里查看示例:https://play.golang.org/p/xKkFLoMXX1s
- https://golang.org/doc/effective_go.html#allocation_new
- https://golang.org/doc/effective_go.html#composite_literals
英文:
Here is a difference: for a Person
struct, the JSON string marshalled from &[]*Person{}
is []
and from new([]*Person)
is null
using json.Marshal
.
Check out the sample here: https://play.golang.org/p/xKkFLoMXX1s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论