When should `new` be used in Go?

前端 未结 2 685
慢半拍i
慢半拍i 2021-01-18 22:57

It seems pointless to be used in primitive language constructs, as you can\'t specify any sort of values

func main() {
    y := new([]float)
    fmt.Printf(\         


        
相关标签:
2条回答
  • 2021-01-18 23:25

    You can't use new for slices and maps, as in your code example, but instead you must use the make command: make([]float, 100)

    Both new(MyStruct) and &MyStruct{} do to the same thing, because Go will allocate values on the heap if you get their address with &. Sometimes the code just expresses it intent better in one style or the other.

    Go does not have built-in support for constructors, so usually you would wrap the call to new into a function, for example NewMyStruct() which does all the necessary initialization. It also makes it possible to initialize private fields or hide the struct behind an interface, to prevent users of the object from directly messing with its internals. Also evolving the structure of the struct is easier that way, when you don't need to change all of its users when adding/removing/renaming/reordering fields.

    0 讨论(0)
  • 2021-01-18 23:32

    make does only work for maps, slices and channels and composite literals like type{} work only for structs, arrays, slices, and maps. For other types, you'll have to use new to get a pointer to a newly allocated instance (if you don't want to use a longer var v T; f(&v)).

    I guess this is useful if you want to initialize a struct:

    typedef foo struct {
        bar *int
    }
    v := foo{bar: new(int)}
    
    0 讨论(0)
提交回复
热议问题