Junior — Middle
Can the initial length of a slice be set when creating it?
sobes.tech AI
Answer from AI
In Go, when creating a slice, you can set the initial length using the make function. Syntax: make([]T, length, capacity), where length is the initial length of the slice, and capacity is its capacity (optional parameter). For example:
s := make([]int, 5) // slice of length 5 and capacity 5
In this case, the slice s will have a length of 5, and all elements will be initialized with the default value for type int (which is 0). You can also specify a capacity larger than the length:
s := make([]int, 5, 10) // length 5, capacity 10
Thus, yes, you can set the initial length of a slice.