Unveiling the Optimal Method to Initialize an Empty Slice
When declaring an empty slice with a flexible size, the question arises: Which is the preferred initialization approach - make([]int, 0) or []int{}?
Both options lead to semantically identical results. However, make([]int, 0) triggers an internal call to runtime.makeslice in Go 1.16.
Alternatively, you can opt for a nil value:
var myslice []int
As stated in the Golang.org blog, a nil slice functions like a zero-length slice despite pointing to nothing. Its length is zero, and it allows appending with allocation.
However, note that a nil slice serializes as "null" in JSON, while an empty slice renders as "[]".
Regardless of the chosen method, none will trigger memory allocation, as clarified by @ArmanOrdookhani.
The above is the detailed content of `make([]int, 0) vs. []int{} vs. nil: What's the Best Way to Initialize an Empty Slice in Go?`. For more information, please follow other related articles on the PHP Chinese website!