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

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

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-24 11:35

    Yes, there is a fundamental difference between the two code fragments.

    v := &Vector{}
    

    Works only for Vector being a struct type, map type, array type or a slice type

    v := new(Vector)
    

    Works for Vector of any type.

    Example: http://play.golang.org/p/nAHjL1ZEuu

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题