When should `new` be used in Go?

前端 未结 2 688
慢半拍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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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)}
    

提交回复
热议问题