【Go】slice

slice Students who are familiar with Javascript should think that it is the slice method of Array, the slice method

go slice, we understand it as an iterator, and this iterator includes two subscript indicators

Definition

1
2
3
4
5
6
7
8
// identifies s as a slice, this slice will point to an array of [] int
var s []int

//
arr: = [6]int {1, 2, 3, 4, 5, 6}

// s This slice is initialized to the area of ​​the original array arr subscript [1, 3)
var s []int = arr [1: 3]

Let’s look at a complete example

1
2
3
4
5
6
7
8
9
10
11
package main

import "fmt"

func main () {
    arr: = [5]int {1, 2, 3, 4, 5}

    var s []int = arr[1: 3]

    fmt.Println(s)
}

Save as helloworld.go and execute the result

1
2
[me @ VM_0_14_centos go] # go run helloworld.go
[2 3]

bottom

A slice slice simply describes a reference to the elements of the array interval (x, y) .The slice slice itself does not store any data.

Modifying the switching elements will directly affect the elements in the original array

Default behavior of slice

slice has a certain default behavior

The default value of the slice lower bound is 0
The upper bound is the switching length

Such as

1
2
3
4
5
6
7
var a [10]int

// The following slices are equivalent a [0:10]
a [0: 10]
a [: 10]
a [0: 0]
a [:]

Slice length and capacity

Slicing has two concepts of length and capacity

Switch length refers to the number of elements it contains, which can be obtained by the expression len (s)
Switching capacity is the number of switching the first element to the last element of the underlying array that it points to, which can be obtained by cap (s)

1
2
3
4
5
6
7
8
9
s: = []int {1, 3, 4, 5, 6, 8}

s = s[2: 5]

// s length is 3
len(s)

// s capacity is 4
cap(4)

Zero value of slice

When the slice switch is not initialized, it is nil

nil has a length and capacity of 0, and there is no underlying reference array

Persist in original technology sharing, your support will encourage me to continue to create!