之间的区别是什么

之间的区别是什么

本文介绍了(* T)(nil)和& T {} / new(T)之间的区别是什么? Golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有人可以解释这两个符号之间的细微差别: 完全等价:分配一个零T并返回一个指向这个分配的内存的指针。唯一的区别是,& T {} 不适用于内置类型,如 int ;你只能做 new(int)。 (* T)( nil) does not 分配一个 T 它只返回一个指向T的零指针。 test3:=(* Struct)(nil)只是混淆了 var test3 * Struct 的模糊变体。 Could anybody explain what the subtle difference between these two notations: (*T)(nil)/new(T) and &T{}. type Struct struct { Field int}func main() { test1 := &Struct{} test2 := new(Struct) test3 := (*Struct)(nil) fmt.Printf("%#v, %#v, %#v \n", test1, test2, test3) //&main.Struct{Field:0}, &main.Struct{Field:0}, (*main.Struct)(nil)}Seems like the only difference of this one (*T)(nil) from other is that it returns nil pointer or no pointer, but still allocates memory for all fields of the Struct. 解决方案 The two forms new(T) and &T{} are completely equivalent: Both allocate a zero T and return a pointer to this allocated memory. The only difference is, that &T{} doesn't work for builtin types like int; you can only do new(int).The form (*T)(nil) does not allocate a T it just returns a nil pointer to T. Your test3 := (*Struct)(nil) is just a obfuscated variant of the idiomatic var test3 *Struct. 这篇关于(* T)(nil)和& T {} / new(T)之间的区别是什么? Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-12 09:27