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

前端 未结 4 2019
遇见更好的自我
遇见更好的自我 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:27

    No. What they return is the same,

    package main
    
    import "fmt"
    import "reflect"
    
    type Vector struct {
        x   int
        y   int
    }
    
    func main() {
        v := &Vector{}
        x := new(Vector)
        fmt.Println(reflect.TypeOf(v))
        fmt.Println(reflect.TypeOf(x))
    }
    

    Result:

    *main.Vector
    *main.Vector
    

    There is some contention on the mailing list that having both is confusing:

    https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/GDXFDJgKKSs

    One thing to note:

    new() is the only way to get a pointer to an unnamed integer or other basic type. You can write "p := new(int)" but you can't write "p := &int{0}". Other than that, it's a matter of preference.

    Source : https://groups.google.com/d/msg/golang-nuts/793ZF_yeqbk/-zyUAPT-e4IJ

提交回复
热议问题