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

Can someone explain what is 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) 
}

It seems that the only difference between this (*T)(nil)and the other is that it returns a nil pointer or not a pointer, but still allocates memory for all Struct fields.

+4
source share
1 answer

new(T) &T{} : T . , &T{} , int; new(int).

(*T)(nil) T, nil T. test3 := (*Struct)(nil) - var test3 *Struct.

+10

Source: https://habr.com/ru/post/1570354/


All Articles