Home >Backend Development >Golang >`make([]int, 0)` vs. `[]int{}`: What's the Best Way to Initialize an Empty Slice in Go?
Best Practice for Initializing Empty Slices
In Go, creating an empty slice with a non-fixed size can be achieved using two methods:
Which approach is considered the correct way depends on the following factors:
Semantic Equivalence:
Both methods result in an empty slice. They are semantically identical and will behave the same way in most scenarios.
Internal Implementation:
Performance:
None of the above options involve any allocation. So, there is no performance difference between them.
Other Options:
You can also declare an empty slice using a nil value:
However, note that a nil slice is functionally equivalent to an empty slice, but it points to nothing.
JSON Marshaling:
Ultimately, the choice between make() and []{} is primarily a matter of preference. However, it's important to be aware of the differences in internal implementation when choosing between the two options.
The above is the detailed content of `make([]int, 0)` vs. `[]int{}`: 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!