gpt4 book ai didi

go - Go 中的 new(Struct) 和 &Struct{} 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 13:10:36 25 4
gpt4 key购买 nike

它们似乎是一样的:

package main

import "fmt"

type S struct {
i int
}

func main() {
var s1 *S = new(S)
fmt.Println(s1)

var s2 *S = &S{}
fmt.Println(s2) // Prints the same thing.
}

更新:

嗯。我刚刚意识到没有明显的方法可以使用 new 初始化 S.i。有没有办法做到这一点? new(S{i:1}) 似乎不起作用:/

最佳答案

来自 Effective Go :

As a limiting case, if a composite literal contains no fields at all, it creates a zero value for the type. The expressions new(File) and &File{} are equivalent.

关于go - Go 中的 new(Struct) 和 &Struct{} 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420596/

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