Sobes.tech
Junior — Middle

What is the difference between the length and capacity parameters of an array in programming?

sobes.tech AI

Answer from AI

In Go, arrays have a fixed length, which is set at creation and cannot be changed. The length parameter of an array is the number of elements it contains, and it is fixed.

Capacity is the number of elements that an array or slice can hold without allocating additional memory. For arrays, capacity equals length since they are fixed. For slices, capacity can be greater than length because slices are dynamic structures that can expand.

Example:

arr := [5]int{1, 2, 3, 4, 5} // length and capacity are both 5

slice := arr[1:3]             // slice length is 2 (elements at indices 1 and 2)
// slice capacity is 4 (from index 1 to the end of the array)

fmt.Println(len(slice)) // 2
fmt.Println(cap(slice)) // 4

Thus, length is the current size (number of elements), and capacity is the maximum size without reallocating memory.

What is the difference between the length and… - sobes.tech