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

前端 未结 4 2023
遇见更好的自我
遇见更好的自我 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条回答
  •  太阳男子
    2020-12-24 11:44

    Here is a difference: for a Person struct, the JSON string marshalled from &[]*Person{} is [] and from new([]*Person) is null using json.Marshal.

    Check out the sample here: https://play.golang.org/p/xKkFLoMXX1s

    • https://golang.org/doc/effective_go.html#allocation_new
    • https://golang.org/doc/effective_go.html#composite_literals

提交回复
热议问题