Slices and variables are different in the Go language: slices are reference types that refer to the underlying array, while variables store values directly. Assignment to a variable creates a new copy, while assignment to a slice creates a new slice pointing to the same array. Slices use references, so modifying one slice may affect other slices that reference the same array, but variables are not affected.
The slice in the Go language is a reference type that can point to the underlying array. This is unlike a variable, which stores its value directly.
A slice consists of three parts:
mySlice := []int{1, 2, 3} // 创建一个整型切片,包含元素 1、2 和 3
Variables store their values directly instead of referencing the underlying data structure.
myVar := 1 // 创建一个整型变量,值为 1
1. Assignment
Assigning a value to a variable will create a new copy of the variable:
var1 := 1 var2 := var1 var1 = 2 // 修改 var1 的值 fmt.Println(var1, var2) // 输出:2 1
And slicing Making an assignment creates a new slice pointing to the same underlying array:
slice1 := []int{1, 2, 3} slice2 := slice1 slice1[0] = 4 // 修改 slice1 中的元素 fmt.Println(slice1, slice2) // 输出:\[4 2 3\] \[4 2 3\]
2. Memory Management
Variables store their values directly, so allocating new variables does not affect other variable. Slices use references, so modifying a slice may affect other slices that reference the same underlying array.
3. Passing to functions
Variables are passed to functions as values, while slices are passed to functions as references. This means that functions can modify slices, but not variables.
Consider a function that accepts a slice and sorts it. The variables nums
and result
are treated as two different slices, even though they refer to the same underlying array.
func sortSlice(nums []int) { sort.Ints(nums) // 对切片排序 } func main() { nums := []int{3, 1, 2} result := nums fmt.Println(nums) // 输出:\[3 1 2\] sortSlice(result) // 对 result 进行排序 fmt.Println(nums) // 输出:\[1 2 3\] }
The above is the detailed content of Understand the difference between slices and variables in Go language. For more information, please follow other related articles on the PHP Chinese website!