Go new function

type Request struct {
   ...
}

r1 := new(Request)
r2 := &Request{}

what"s the difference between R1 and R2?

I see net/http/request.go
func (r * Request) WithContext (ctx context.Context) * Request
in the standard library new . After reading a lot of materials on the Internet, I can"t find out why I should use new.

.
Oct.05,2021

there is no difference between R1 and R2.

when you don't need to initialize nonzero values for members of a structure, you can use new, the golang built-in primitive

.

this took a look at the effective go, address here.
https://golang.google.cn/doc/.

new does not initialize the object, but instead populates the (zeroed) with zero values.
this is more appropriate to use map for verification.

  

new is faster in terms of efficiency, because new is a pointer that returns an address directly, and there is no initialization process

.
Menu