Slice and array in golang and their differences

Time:2020-10-22

There are two kinds of data structures in golang: array and slice. Slice is an implementation based on array. Slice is a dynamically variable length data structure. In essence, it is a reference to array word sequence and provides lightweight access to array. So today we will give you a detailed introduction to slice and array in golang,

1. Array in golang

Array is a kind of basic data structure with fixed length. In golang, as in C language, once an array is created, its length cannot be changed. The empty position of array is filled with 0, and the array is not allowed to cross the boundary.

     Some basic operations of array:

1. Create array:

func main() {
 Var Arr1 = [...] int {1,2,3,4} / [...] defaults to the number of elements, that is, the length of the array
 fmt.Println(len(arr1)) //4
 Arr1 [4] = 5 // span array out of bounds
 fmt.Println(arr1)
 var arr2 = [10]int{1,2,3,4}
 fmt.Println(arr2) //[1 2 3 4 0 0 0 0 0 0]
}

 2. The array is a value copy pass:

func main() {
 var arr = [10]int{4,5,7,11,8,9}
 fmt.Println(arr) //[4,5,7,11,8,9,0,0,0,0]
 //Verify that the array is a value copy pass
 AddOne(arr)
 fmt.Println(arr) //[4,5,7,11,8,9,0,0,0,0]
}
func AddOne(arr [10]int){
 arr[9] = 999999
 fmt.Println(arr) //[4,5,7,11,8,9,0,0,0,999999]
}

2. Slice in golang 

1. First, look at the source code structure of slice


type slice struct {
 array unsafe.Pointer
 len int
 cap int
}

Slice is a special reference type, but it is also a structure itself

The len attribute indicates the number of available elements. Read and write operations cannot exceed this limit, otherwise it will be panic

The property cap indicates the maximum expansion capacity. Of course, the expansion capacity is not infinite. It is limited by the length of the underlying array array. If the length exceeds the length of the underlying array, it will be panic

    2. Create slice:

func main() {
  var arr = [...]int{0,1,2,3,4,5,6}
  slice1 := arr[1:4:5] //{ low:high : Max} extends at most one more element
  //Max exceeds len (ARR)
  //slice2 := arr[1:4:7] //panic
  fmt.Println(slice1) //[1,2,3]
  Slice3: = slice1 [1:3:4] / [2,3] greater than 4 will panic
  fmt.Println(slice3)
}

In the above code, an array arr with length of 7 is created, and a slice1 based on array arr is created. The slice refers to the elements between index = 1 and index = 3 of the array. At the same time, the slice is allowed to expand the space of 1 element size. If the expansion space is greater than 7, then the program will panic. Finally, a slice2 based on slice1 extension is created. It refers to the elements between index = 1 and index = 3 of the slice. Since slice1 can expand one element at most, slice2 can also expand one element at most, which exceeds the span.

Create a slice based on the underlying array, and its cap value is between len < = cap < = len (ARR)

Create a slice based on a slice, and its cap value is between len (slice1) < = cap < = cap (slice1)

3. Slice is created with make

func main() {
  var slice = make([]int,3,5) //len=3,cap=5
  fmt.Println(slice)  //[0,0,0]
  Slice2: = slice [: 5] // slice implements the expansion of slice, and the slice length becomes 5
  fmt.Println(slice2) //[0,0,0,0,0]
}

  4. Slice as parameter

func main() {
  var slice = make([]int,3,5) //len=3,cap=5
  fmt.Println(slice)  //[0,0,0]
  Slice2: = slice [: 5] // slice implements the expansion of slice, and the slice length becomes 5
  fmt.Println(slice2) //[0,0,0,0,0]
  Slice [0] = 999 // here, the index = 0 position of slice and slice are both 999, because the index = 0 position of the underlying array they refer to is 999
  fmt.Println(slice)
  fmt.Println(slice2)
  AddOne(slice) //[8888,0,0]
  fmt.Println(slice) //[8888,0,0]
  fmt.Println(slice2) //[8888,0,0,0]
}
func AddOne(s []int){
 s[0] = 8888
 fmt.Println(s)
}

Because slice is a reference type, it is passed to the function as an argument. The essence of function operation is the underlying array

3. Append() to slices in golang

func main() {
  var arr = [...]int{1,2,3,4}
  fmt.Println(arr) //[1,2,3,4]
  slice := arr[:]
  fmt.Println(slice) //[1,2,3,4]
  Slice = append (slice, [] int {5,6,7}...) // at this time, the reference address of slice has changed. The underlying array it refers to is no longer arr, but a new array newarr [1,2,3,4,5,6,7]
  fmt.Println(slice) //[1,2,3,4,5,6,7]
  //Verify that the address referenced by slice has changed
  slice[0] = 666
  fmt.Println(arr) //[1,2,3,4]
  fmt.Println(slice) //[666,2,3,4,5,6,7]
}

Here, because the element added by slice exceeds the size of the original array, go will help us create a new underlying array. The reference address of slice is no longer arr, but becomes a newly created array.

Another case is that when the slice is appended, its reference address does not change when it does not exceed the size of the original array.


func main() {
  var arr = [6]int{1,2,3,4}
  fmt.Println(arr) //[1,2,3,4,0,0]
  slice := arr[:4]
  fmt.Println(slice) //[1,2,3,4]
  slice = append(slice,5)
  fmt.Println(arr) //[1,2,3,4,5,0]
  fmt.Println(slice) //[1,2,3,4,5]
}

4. Summary

(1) Go has an array, but it usually uses more slices. Once the array size is created, it cannot be changed. When the array length is greater than the number of elements, 0 will be used to fill the place. This is similar to other languages.

(2) Slice can be regarded as all operations on an array. It is a reference data type. Its data structure includes the address of the underlying array and the operable length len or expandable length cap.

(3) In order to break through the cap limit of slice for unlimited expansion, you need to use the append() function. If the total length of slices after appending elements does not exceed the total length of the underlying array, the address referenced by slice will not change, otherwise, the reference address will become the address of the new array.

(4) Slice is an abstract concept. The meaning of its existence is to facilitate some convenient operations on a sequential structure, such as searching, sorting, appending, etc., which is similar to the python list.

Let’s look at the difference between golang array and slice

The difference between golang array and slice

When initializing, declare the length of the array

Variable length of slice

var a [32] int

var b [3][5] int

A and B have different types

When creating a slice, you can not specify the length.

summary

This article on the golang slice and array and the difference between the detailed article introduced here, more related golang slice data content, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!

Recommended Today

Java security framework

The article is mainly divided into three parts1. The architecture and core components of spring security are as follows: (1) authentication; (2) authority interception; (3) database management; (4) authority caching; (5) custom decision making; and;2. To build and use the environment, the current popular spring boot is used to build the environment, and the actual […]