Go language slice


Release date:2023-09-19 Update date:2023-10-13 Editor:admin View counts:218

Label:

Go language slice

Go language slicing is an abstraction of an array.

The length of the Go array is immutable, so such a set is not suitable in a particular scene. Go provides a flexible, powerful built-in type slice (“dynamic array”), the length of the slice is not fixed compared with the array, you can append elements, when appended may increase the capacity of the slice.

Define slicing

You can declare an array of unspecified sizes to define slices:

var identifier []type

The length of the slice does not need to be specified.

Or use the make() function to create a slice:

var slice1 []type = make([]type, len)

It can also be abbreviated as

slice1 := make([]type, len)

You can also specify the capacity, where capacity is an optional parameter.

make([]T, length, capacity)

Here len is the length of the array and the initial length of the slice.

Slice initialization

s :=[] int {1,2,3 }

Directly initialize the slice [] indicates a slice type {1,2,3} The initialization values in turn are 1, 2, 3, and its cap=len=3 .

s := arr[:]

Initialize slicing s is an array, arr is a quote.

s := arr[startIndex:endIndex]

Set arr middle from subscript startIndex to endIndex-1, the element under is created as a new slice.

s := arr[startIndex:]

By default, endIndex will represent the last element up to arr.

s := arr[:endIndex]

By default, startIndex will represent a change from the arr, begins with the first element.

s1 := s[startIndex:endIndex]

Initialize slice s1 with slice s.

s :=make([]int,len,cap)

Initialize the slice s through the built-in function make(), and identify it as the slice whose element type is int.

Len() and cap() functions

Slices are indexable and can be defined by the len() method to get the length.

Slicing provides a method for calculating capacity, which can measure the maximum length that a slice can reach.

The following are specific examples:

Example

package main
import "fmt"
func main() {
   var numbers = make([]int,3,5)
   printSlice(numbers)
}
func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\\n",len(x),cap(x),x)
}

The output of the above instance is as follows:

len=3 cap=5 slice=[0 0 0]

Empty (nil) slice

A slice defaults to nil and has a length of 0 before initialization. The example is as follows:

Example

package main
import "fmt"
func main() {
   var numbers []int
   printSlice(numbers)
   if(numbers == nil){
      fmt.Printf("Slice is empty")
   }
}
func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\\n",len(x),cap(x),x)
}

The output of the above instance is as follows:

len=0 cap=0 slice=[]
Slice is empty

Slice truncation

You can set the truncation slice by setting the lower and upper limits [lower-bound:upper-bound], the example is as follows:

Example

package main
import "fmt"
func main() {
   /* Create Slice */
   numbers := []int{0,1,2,3,4,5,6,7,8}
   printSlice(numbers)
   /* Print original slices */
   fmt.Println("numbers ==", numbers)
   /* Printing sub slices from index 1 (included) to index 4 (not included)*/
   fmt.Println("numbers[1:4] ==", numbers[1:4])
   /* The default lower limit is 0*/
   fmt.Println("numbers[:3] ==", numbers[:3])
   /* Default upper limit is len (s)*/
   fmt.Println("numbers[4:] ==", numbers[4:])
   numbers1 := make([]int,0,5)
   printSlice(numbers1)
   /* Printing sub slices from index 0 (included) to index 2 (not included) */
   number2 := numbers[:2]
   printSlice(number2)
   /* Printing sub slices from index 2 (included) to index 5 (not included) */
   number3 := numbers[2:5]
   printSlice(number3)
}
func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\\n",len(x),cap(x),x)
}

The output result of executing the above code is:

len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
len=0 cap=5 slice=[]
len=2 cap=9 slice=[0 1]
len=3 cap=7 slice=[2 3 4]

append() and copy() function

If we want to increase the capacity of the slice, we must create a new and larger slice and copy the contents of the original slice.

The following code describes the copy of the sliced copy method and append a new element to the slice append method.

Example

package main
import "fmt"
func main() {
   var numbers []int
   printSlice(numbers)
   /* Allow adding empty slices */
   numbers = append(numbers, 0)
   printSlice(numbers)
   /* Add an element to the slice */
   numbers = append(numbers, 1)
   printSlice(numbers)
   /* Adding multiple elements simultaneously */
   numbers = append(numbers, 2,3,4)
   printSlice(numbers)
   /* Create slice numbers1 is twice the capacity of the previous slice*/
   numbers1 := make([]int, len(numbers), (cap(numbers))*2)
   /* Copy the contents of numbers to numbers1 */
   copy(numbers1,numbers)
   printSlice(numbers1)
}
func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\\n",len(x),cap(x),x)
}

The output of the above code execution is as follows:

len=0 cap=0 slice=[]
len=1 cap=1 slice=[0]
len=2 cap=2 slice=[0 1]
len=5 cap=6 slice=[0 1 2 3 4]
len=5 cap=12 slice=[0 1 2 3 4]

Powered by TorCMS (https://github.com/bukun/TorCMS).