考虑以下示例:
type House struct{}
func main() {
house1 := new(House)
house2 := &House{}
fmt.Printf("%T | %T\n", house1, house2)
}
输出:*main.House | *main.House
两个赋值都会产生一个指向类型的指针House(来自 main 包)。
从 go 文档中new:
// 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.
两种分配的内存分配在技术上是否相同?有最佳实践吗?
守着星空守着你
相关分类