Allocating Arrays with Variable Size in Go
Unlike constant-sized arrays declared using const, Go does not allow the direct allocation of arrays with runtime-determined sizes. This is evident in the following illegal code:
n := 1 var a [n]int
However, there is a solution: utilize slices instead of arrays. Slices are references to underlying arrays and provide dynamic resizing capabilities. The built-in make() function is used to create slices and their underlying arrays. It takes three arguments:
By creating a slice using make(), we indirectly allocate an array with a runtime size:
n := 12 s := make([]int, n, 2*n)
In this case, an array of size 2*n is allocated, and s refers to a slice containing the first n elements of the array.
It remains unclear why Go does not allow direct allocation of variable-sized arrays, but the solution of using slices provides a flexible and efficient alternative. As a result, it is recommended to use slices in most scenarios when working with dynamic data structures in Go.
The above is the detailed content of How Can I Allocate Arrays with Variable Size in Go?. For more information, please follow other related articles on the PHP Chinese website!