问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/27827871/what-the-difference-between-tnil-and-t-newt-golang