doumanshan6314 2018-12-01 22:43 采纳率: 0%
浏览 691
已采纳

make(map)和map {}之间的区别

Just wondering what the difference is between:

z := make(map[*test] string)

and

z := map[*test] string{}

am I imagining things or are they both not valid?

  • 写回答

2条回答 默认 最新

  • doukuangxun5382 2018-12-01 23:24
    关注

    The Go Programming Language Specification

    Making slices, maps and channels

    The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

    Call         Type T  Result
    make(T)      map     map of type T
    make(T, n)   map     map of type T with initial space for approximately n elements
    

    Composite literals

    Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

    map[string]int{}
    map[string]int{"one": 1}
    

    make is the canonical form. Composite literals are a convenient, alternate form.

    z := make(map[int]string)
    

    and

    z := map[int]string{}
    

    are equivalent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?