gpt4 book ai didi

go - new() 和 "regular"分配有区别吗?

转载 作者:IT老高 更新时间:2023-10-28 12:59:54 27 4
gpt4 key购买 nike

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

v := &Vector{}

相对

v := new(Vector)

最佳答案

没有。他们返回的都是一样的,

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

关于go - new() 和 "regular"分配有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com