new()和"regular"之间是否有区别?分配? [英] Is there a difference between new() and "regular" allocation?

查看:45
本文介绍了new()和"regular"之间是否有区别?分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,以下两段代码之间存在显着差异:

In Go, is there a notable difference between the following two segments of code:

v := &Vector{}

相对于

v := new(Vector)

推荐答案

否.他们返回的是一样的

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))
}

结果:

*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

需要注意的一件事:

new()是获取指向 未命名的整数或其他基本类型.您可以编写"p:= new(int)",但 您不能写"p:=& int {0}".除此之外,这是一个问题 偏好.

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.

来源: https://groups.google.com /d/msg/golang-nuts/793ZF_yeqbk/-zyUAPT-e4IJ

这篇关于new()和"regular"之间是否有区别?分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆