Home >Backend Development >Golang >`make([]int, 0) vs. []int{} vs. nil: What's the Best Way to Initialize an Empty Slice in Go?`

`make([]int, 0) vs. []int{} vs. nil: What's the Best Way to Initialize an Empty Slice in Go?`

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 14:12:10428browse

`make([]int, 0) vs. []int{} vs. nil: What's the Best Way to Initialize an Empty Slice in Go?`

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn