Junior — Middle
Kuidas eristada Go-s lõigu loomise viise, kasutades var, make ja määramist indeksite või appendi kaudu?
sobes.tech AI
Vastus AI-lt
In Go, slices can be created in various ways, which differ in initialization and memory allocation:
- Declaration with
var— creates a nil slice, which does not point to any array and has length and capacity 0.
var s []int // nil slice
- Creating a slice using
make— allocates an array with specified length and capacity, and returns a slice pointing to this array.
s := make([]int, 5) // slice of length 5, filled with zeros
-
Assignment by indices — only possible if the slice is already initialized and has sufficient length.
-
Adding elements with
append— adds elements to the slice, and if necessary, increases capacity and allocates a new array.
s = append(s, 10) // adds element 10 to the slice
Thus, var creates an empty nil slice, make creates a slice with allocated memory, index assignment requires an existing length, and append dynamically expands the slice.