Is there a difference between new() and “regular” allocation?

前端 未结 4 2018
遇见更好的自我
遇见更好的自我 2020-12-24 11:01

In Go, is there a notable difference between the following two segments of code:

v := &Vector{}

as opposed to

v := new(         


        
4条回答
  •  -上瘾入骨i
    2020-12-24 11:22

    According to Effective Go, new() is a function that allocates memory, and zeros it out; that is every field (and the entire piece of memory for the structure) will be set to 0s. If you design your structures so that when they're created all fields should equal zero, than it's fine and recommended to use it. If, however, you need more control over what initial values are to be used, then the more conventional method should be used.

    In the specific case you mention the difference is irrelevant, but it should be noted elsewhere.

    I hope this helps! :)

提交回复
热议问题