Semantic understanding slice
Slicing in go language is a feature of go language. Semantically speaking, slicing is to cut a whole thing into small parts, so it is the same with slicing in language.
For example, consider the following code:
package main
import "fmt"
func main() {
arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
fmt.Println ("arr [2:6]", arr [2:6]) // from subscript 2 to subscript 6
fmt.Println ("arr [: 6]", arr [: 6]) // from subscript 0 to subscript 6
fmt.Println ("arr [2:]", arr [2:]) // from subscript 2 to the end
fmt.Println ("arr [:]", arr [:]) // all
}
The output results are as follows:
arr[2:6]: [2 3 4 5]
arr[:6]: [0 1 2 3 4 5]
arr[2:]: [2 3 4 5 6 7]
arr[:]: [0 1 2 3 4 5 6 7]
We can clearly see that we can cut the part of arr array that we want.
Of course, it is not enough to know that slicing is used in this way, but we should have a deeper understanding
Copy or view the original array.
For go arrays, copy and view exist at the same time.
- Copy means that when I use this array, I will copy the array, so that the value of the original array will not be changed if the array is added, deleted or modified
- View the returned object is a view, that is, a view. If we operate the array on the view, the original array will be changed,
Copy scenario
package main
import (
"fmt"
)
func updateArr(arr [5]int) {
arr[0] = 100
fmt.Println ("modified arr:", ARR)
}
func main() {
arr3 := [...]int{2, 4, 5, 6, 7}
fmt.Println ("Original:" arr3)
updateArr(arr3)
fmt.Println ("view original again?", arr3)
}
Output results:
Original: [24 5 6 7]
Modified arr: [100 4 5 6 7]
Look again at the original: [24 5 6 7]
As can be seen from the above code, we changed the value with the subscript of 0 in the updatearr, but it did not change when we output the original array. This is the copy of an array.
View scene
func updateArr(arr []int) {
arr[0] = 100
fmt.Println ("modified arr:", ARR)
}
func main() {
arr3 := [...]int{2, 4, 5, 6, 7}
fmt.Println ("Original:" arr3)
//Using slices
updateArr(arr3[:])
fmt.Println ("view original again?", arr3)
}
Output results:
Original: [24 5 6 7]
Modified arr: [100 4 5 6 7]
Look again at the original: [100 4 5 6 7]
Why can view change the original array
Although slice itself is a value type, it uses a pointer reference to the array internally, so modifying the slice data will modify the original data of the array.
Of course, while understanding the above, we must know how go defines a slice
var b []int
Therefore, when the updatearr function transfers parameters, arr [] int is passed to the slice. Otherwise, the report will be wrong.
The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.