The declaration and use of slice in Go language

1. The definition of slice

    Slice in Go language is a kind of dynamic array, which is an extension of array.

  • Compared with arrays, the length of the cut is not fixed, and elements can be added, which may increase the capacity of the cut.
  • The cut itself does not have any data, they are just references to existing arrays.
  • The cut is relative to the array, there is no need to set the length, and the setting value is not used in [], which is relatively free.
  • Conceptually, a slice is like a structure. This structure contains three elements:
    1) Pointer, pointing to the starting position specified by the slice in the array;
    2) Length, which is the length of the slice;
    3) Maximum Length, that is, the length from the beginning of the slice to the last position of the array.

Second, the syntax of slices

2.1 Declare slice

    2.1.1 Declare an array of unspecified length to define the cut

  • was identifier [] type
  • There is no need to explain the length;
  • The statement mode, and the uninitialized switch is an empty switch. This cut is nil by default, and its length is 0.

    2.1.2 Use the make() function to create cuts:

  • var slice1 []type = make([]type, len)
  • Can be abbreviated as: slice1 := make([]type, len)
  • You can specify capacity, where capacity is an optional parameter: make([]T, length, capacity)

//mySlice.go

package main

import (
	"fmt"
)

func main() {
    
    
	//fmt.Println("Hello World!")
	//1)切片
	var numbers = make([]int, 3, 5)
	fmt.Printf("%T\n", numbers)
	fmt.Printf("len=%d cap=%d slice=%v\n", len(numbers), cap(numbers), numbers)
}

The effect is as follows:

Figure (1) Print the length, capacity and data elements of the slice

2.2 Initialization

2.2.1 Directly initialize the slice

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

2.2.2 Initializing slices through array interception

   数组: arr := [5]int {1,2,3,4,5}
  • 1) s := arr[:]
    contains all the elements of the array
  • 2) s := arr[startIndex:endIndex]
    creates the element under the subscript startIndex to endIndex-1 in arr as a new cut (closed before and opened), the length is endIndex-startIndex
  • 3) s := arr[startIndex:]
    will indicate the last element up to the last element of arr by default endIndex;
  • 4) s := arr[:endIndex]
    will start from the first element of arr by default.

2.2.3 Initialize slice by slice interception

    You can set the interception cut by setting the lower limit and upper limit [lower-bound:upper-bound]
//mySlice2.go

package main

import (
	"fmt"
)

func printSlice(x []int) {
    
    
	fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}

func main() {
    
    
	//fmt.Println("Hello World!")
	//1)切片
	// var numbers = make([]int, 3, 5)
	// fmt.Printf("%T\n", numbers)
	// fmt.Printf("len=%d cap=%d slice=%v\n", len(numbers), cap(numbers), numbers)

	//2)截取切片
	numbers := []int{
    
    0, 1, 2, 3, 4, 5, 6, 7, 8}
	printSlice(numbers)

	//打印原始切片
	fmt.Println("numbers== ", numbers)

	//打印子切片,从索引1到索引4,左闭右开,[1,4)
	fmt.Println("numbers[1:4]== ", numbers[1:4])

	//默认下限为0,[0,3)
	fmt.Println("numbers[:3]== ", numbers[:3])

	//默认上限为len(s),[4,len(s))
	fmt.Println("numbers[4:]== ", numbers[4:])

	//打印子切片,[0,2)
	number2 := numbers[:2]
	printSlice(number2)

	//打印子切片,[2,5)
	number3 := numbers[2:5]
	printSlice(number3)
}

    The effect is as follows:

Figure (2) Through the interception method, to obtain the slice

Three, the len() and cap() functions in the slice

  • The degree of cut is the number of elements in the cut.
  • The capacity of a cut is the number of elements in the underlying array starting from the index where the cut was created.
  • The cut is indexable, and the length can be obtained by the len() method. The cut provides a method for calculating the capacity, cap(), which can measure the maximum length of the cut. [The result of array calculation cap() is the same as len()].
  • What is practical is to get a certain part of the array, len cut<=cap cut<=len array.
  • The result of cap() determines the attention details of the cut interception.
    //mySlice02.go
// mySliceCap project main.go
package main

import (
	"fmt"
)

func main() {
    
    
	sliceCap()
}

func sliceCap() {
    
    
	arry := [...]string{
    
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}
	fmt.Println("cap(arry)= ", cap(arry), arry)

	//截取数组,形成切片
	sli01 := arry[2:8]
	fmt.Printf("%T\n", sli01)
	fmt.Println("cap(sli01)= ", cap(sli01), sli01)

	sli02 := arry[4:7]
	fmt.Println("cap(sli02)= ", cap(sli02), sli02)

	//截取切片,形成切片
	sli03 := sli01[3:9]
	fmt.Println("截取sli01[3:9]后形成sli03: ", sli03)

	sli04 := sli02[4:7]
	fmt.Println("截取sli02[4:7]后形成sli04: ", sli04)

	//切片是引用类型
	sli04[0] = "x"
	fmt.Print(arry, sli01, sli02, sli03, sli04)

}


    The results are as follows:

Figure (3) The cap() function in the slice

Fourth, the slice is a reference type

  • A slice does not have any data of its own, it is just a reference to the underlying array, and any modifications made to the slice will be reflected in the underlying array.
  • Arrays are value types, but they are reference types.

    The case of modifying the array is as follows:
//mySlice04.go

// mySliceCmp project main.go
package main

import (
	"fmt"
)

func main() {
    
    
	a := [4]float64{
    
    67.7, 89.8, 21, 78}
	b := []int{
    
    2, 3, 5}
	fmt.Printf("变量a -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &a, a, a, len(a))
	fmt.Printf("变量b -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &b, b, b, len(b))
	c := a
	d := b
	fmt.Printf("变量c -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &c, c, c, len(c))
	fmt.Printf("变量d -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &d, d, d, len(d))
	a[1] = 200
	fmt.Println("a= ", a, " c= ", c)
	d[0] = 100
	fmt.Println("b= ", b, " d= ", d)
}

    The results are as follows:

Figure (4) Modify the value in the array
  • Modifying the cut value
        When multiple pages share the same underlying array, the changes made by each element will be reflected in the array.
        Modify the value in the slice, the example is as follows:
    //mySlice04.go
// mySliceChg project main.go
package main

import (
	"fmt"
)

func main() {
    
    
	//定义数组
	arry := [3]int{
    
    1, 2, 3}

	//根据数组截取切片
	nums1 := arry[:]
	nums2 := arry[:]
	fmt.Println("arry= ", arry)

	nums1[0] = 100
	fmt.Println("arry= ", arry)

	nums2[1] = 200
	fmt.Println("arry= ", arry)

	fmt.Printf("变量arry  --地址: %p\n", &arry)
	fmt.Printf("变量nums1 --地址: %p\n", &nums1)
	fmt.Printf("变量nums2 --地址: %p\n", &nums2)
}

    The results are as follows:

Figure (5) Modify the value in the slice

Guess you like

Origin blog.csdn.net/sanqima/article/details/108895065