(* T)(nil)和& T {} / new(T)之间的区别是什么? Golang [英] What the difference between (*T)(nil) and &T{}/new(T)? Golang
问题描述
有人可以解释这两个符号之间的细微差别:(* T)(nil)/ new(T)
和& T {}
。
类型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)
}
看起来像这个唯一的区别(* T)(nil)
from other是它返回nil指针或没有指针,但仍然为struct的所有字段分配内存。
new(T)
和& T {} / code>完全等价:分配一个零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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!