Senior
What is a slice in Go? How does it differ from an array? What happens when passing a slice to a function and modifying its elements?
sobes.tech AI
Answer from AI
A slice in Go is a dynamic, resizable view of an array's elements. Unlike an array, which has a fixed length and size, a slice contains a pointer to an array, a length, and a capacity.
Main differences between a slice and an array:
- An array has a fixed size, specified at declaration, for example:
var arr [5]int. - A slice is a structure that references a part of an array, for example:
var s []int. - A slice can be extended and its length can be changed using built-in functions, whereas an array cannot.
When passing a slice to a function, a copy of the slice structure (pointer to the array, length, capacity) is passed, but the array elements themselves are not copied. Therefore, if you modify the elements of the slice inside the function (e.g., s[0] = 10), the changes will be visible outside, since the slice points to the same array.
Example:
func modify(s []int) {
s[0] = 100
}
func main() {
arr := [3]int{1, 2, 3}
s := arr[:]
modify(s)
fmt.Println(arr) // Will output [100 2 3]
}