Declaring a Portion: var or make?
In Go, portions are an essential data structure. However, there are two different ways to declare a portion:
var s []int
This declaration creates a worthless portion, that is, a portion that does not stores any element. The reference value of s is nil.
s := make([]int, 0)
This statement creates an empty slice, that is, a slice with zero elements but with allocated memory. The reference value of s is not nil.
What's the Difference?
The main difference between these two declarations is that var declares a valueless portion while which make allocates memory for an empty chunk. Using var creates a chunk that initially has no storage space allocated to it. No elements can be stored in the slice until memory is allocated to it.
On the other hand, make allocates memory for an empty slice, which means that elements can be stored in it immediately. However, the initial portion size is zero, so it is important to increase the portion size if more items are to be stored.
What is the Best Option?
It is generally recommended to use var to declare a portion if you do not know the exact size of the portion to be used. This allows the slice to grow and resize dynamically as needed.
If the exact size of the slice is known, using make can be more efficient, as it allocates memory immediately and avoids overloading the slice. creation of a worthless portion.
The above is the detailed content of Go Slices: `var` or `make` – Which Declaration is Best?. For more information, please follow other related articles on the PHP Chinese website!