gpt4 book ai didi

go - Go 中通过 new(Type) 和 &Type{} 分配内存的区别

转载 作者:行者123 更新时间:2023-12-02 01:54:32 30 4
gpt4 key购买 nike

考虑以下示例:

type House struct{}

func main() {
house1 := new(House)
house2 := &House{}
fmt.Printf("%T | %T\n", house1, house2)
}

输出:*main.House | *main.House

两个赋值都会生成一个指向 House 类型的指针(来自包 main)。

摘自new的go文档:

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.

这两种分配中的内存分配在技术上是否相同?有最佳实践吗?

最佳答案

Is memory allocation in both assignments technically the same?

我不会谈论实现细节,因为这些细节可能会改变,也可能不会改变。

从语言规范的角度来看,是有区别的。

使用new(T)进行分配遵循allocation的规则(我自己的注释[斜体]):

The built-in function new takes a type T, allocates storage for a variable of that type at run time, and returns a value of type *T pointing to it. The variable is initialized as described in the section on initial values. [its zero value]

使用复合文字作为 &T{} 进行分配遵循 composite literals 的规则和 addressing :

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated.

Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

因此,new(T)&T{} 都分配存储并产生 *T 类型的值。但是:

  • new(T) 接受任何类型,包括预声明的标识符,如 intbool,如果您只需要这样做,这可能会派上用场用一行代码初始化此类变量:
n := new(int) // n is type *int and points to 0
b := new(bool) // b is type *bool and points to false
  • new ( quoting Effective Go ) “不会初始化1该内存,只会将其归零”。 IE。内存位置将具有该类型的零值。
  • 复合文字只能用于结构体、数组、 slice 和映射
  • 复合文字可以通过显式初始化结构体字段或数组/slice/映射项来构造非零值

底线:正如Effective Go 所指出的(与上面的段落相同):

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


[1]:规范和Effective Go 中术语“初始化”的使用不一致。要点是,使用 new 只能产生零值,而复合文字允许您构造非零值。显然,规范才是事实的来源。

关于go - Go 中通过 new(Type) 和 &Type{} 分配内存的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69784973/

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