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.
About nil. nil is a predefined identifier in Go that represents zero values of many types. nil is usually mistaken as null (or NULL) in other languages, but they are different. Note: nil can be used without declaring it.
nil s in Go. nil is a frequently used and important predeclared identifier in Go. It is the literal representation of zero values of many kinds of types. Many new Go programmers with experiences of some other popular languages may view nil as the counterpart of null (or NULL ) in other languages.
In the Go programming language, nil is a zero value. Recall from unit 2 that an integer declared without a value will default to 0. An empty string is the zero value for strings, and so on. A pointer with nowhere to point has the value nil .
If the concrete value inside the interface itself is nil, the method will be called with a nil receiver. In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With