Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between (*T)(nil) and &T{}/new(T)? Golang

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.

like image 749
Timur Fayzrakhmanov Avatar asked Jan 07 '15 20:01

Timur Fayzrakhmanov


People also ask

What does nil mean in Golang?

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.

Why does Golang use nil instead of null?

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.

How do you use nil in Golang?

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 .

Can an interface be 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.)


1 Answers

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.

like image 142
Volker Avatar answered Oct 19 '22 07:10

Volker