Usage of copy and view for go slices

  • 2020-09-16 07:32:01
  • OfStack

Semantic understanding slice

Slicing in go language is a feature of go language. Semantically, slicing is to cut a whole thing into small parts. The same is true for slicing in language.

Take the following code for an example:


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 the subscript 2 The subscript 6
 fmt.Println("arr[:6]:", arr[:6]) //  From the subscript 0 The subscript 6
 fmt.Println("arr[2:]:", arr[2:]) //  From the subscript 2 In the end 
 fmt.Println("arr[:]:", arr[:]) //  all 
}

The output result is:

[

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]

]

It's pretty clear here that we'll cut whatever part of the arr array we want.

Of course, it's not enough just to know how slices are used, we should have a deeper understanding, such as:

copy or view for the original array.

For arrays of go, both copy and view exist simultaneously.

copy is when I use this array, I make a copy of this array, so that when I add, delete or change the array, I don't change the value of the original array The object that view returns by slicing from the array is 1 view, the view, and if we manipulate the array on the view, it changes the original array,

copy scenario


package main

import (
 "fmt"
)

func updateArr(arr [5]int) {
 arr[0] = 100
 fmt.Println(" The modified arr : ", arr)
}

func main() {
 arr3 := [...]int{2, 4, 5, 6, 7}
 fmt.Println(" The original: ", arr3)
 updateArr(arr3)
 fmt.Println(" Review the original: ", arr3)
}

Output results:

[

Original: [2 4 5 6 7]
Revised arr: [100 4 5 6 7]
Look again at the original: [2 4 5 6 7]

]

As you can see from the above code, in updateArr we changed the value with the index 0, but when we printed out the original array, it didn't change. This is for the array copy.

view scenario


func updateArr(arr []int) {
 arr[0] = 100
 fmt.Println(" The modified arr : ", arr)
}

func main() {
 arr3 := [...]int{2, 4, 5, 6, 7}
 fmt.Println(" The original: ", arr3)
 //  Using slice 
 updateArr(arr3[:])
 fmt.Println(" Review the original: ", arr3)
}

Output results:

[

Original: [2 4 5 6 7]
Revised arr: [100 4 5 6 7]
Look again at the original: [100 4 5 6 7]

]

Why is view able to change the original array

Although Slice itself is a value type, it USES pointer references to arrays internally, so modifying slice data will remove the array's original data.

Of course, in understanding the above, 1 must know how go defines 1 slice


var b []int

So, arr []int is sliced in when the function updateArr passes arguments. Otherwise, you'll get an error.


Related articles: