Go Language---Slice

Source: Internet
Author: User

Go language---slice78893420. Use of array slices:
//1.基于数组创建数组切片    var array [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}    var sliceMy = array[1:7] //array[startIndex:endIndex] 不包含endIndex    //2.直接创建数组切片    slice2 := make([]int, 5, 10)    //3.直接创建并初始化数组切片    slice3 := []int{1, 2, 3, 4, 5, 6}    //4.基于数组切片创建数组切片    slice5 := slice3[:4]    //5.遍历数组切片    for i, v := range slice3 {        fmt.Println(i, v)    }    //6.len()和cap()    var len = len(slice2)  //数组切片的长度    var cap = cap(sliceMy) //数组切片的容量    fmt.Println("len(slice2) =", len)    fmt.Println("cap(slice) =", cap)    //7.append() 会生成新的数组切片    slice4 := append(slice2, 6, 7, 8)    slice4 = append(slice4, slice3...)    fmt.Println(slice4)    fmt.Println(slice5)    //8.copy() 如果进行操作的两个数组切片元素个数不一致,将会按照个数较小的数组切片进行复制    copy(slice2, slice3) //将slice3的前五个元素复制给slice2    fmt.Println(slice2, slice3)
Two. Array slicing data structure analysis:

The data structure of the array slice slice is as follows, a pointer to the real array address ptr,slice the length Len and the capacity cap

// slice 数据结构type slice struct {    array unsafe.Pointer     len   int                cap   int            }

When a parameter is passed, the function receives a copy of the array slice, although the two are different variables, but they all have an array pointer to the same address space, and when an array slice is modified, the other one also changes, so the array slice looks like a reference pass, which is actually a value pass.

Three. Append () method parsing:

3.1 The case of array slicing without expansion

Run the following code to think about a problem: S1 and S2 are pointing to the same underlying array?

func main() {    array := [20]int{1, 2, 3, 4, 5, 6, 7, 8, 9}    s1 := array[:5]    s2 := append(s1, 10)    fmt.Println("s1 =", s1)    fmt.Println("s2 =", s2)    s2[0] = 0    fmt.Println("s1 =", s1)    fmt.Println("s2 =", s2)}

Output Result:
S1 = [1 2 3 4 5]
s2 = [1 2 3 4 5 10]
S1 = [0 2 3 4 5]
S2 = [0 2 3 4 5 10]
As the result of the first and second rows, it seems that this is pointing to two different arrays, but when S2 is modified, it is found that S1 also changes, which in turn indicates that they are pointing to the same set of numbers. What exactly is the truth?
Run the following code:

import (    "fmt"    "unsafe") type Slice struct {    ptr unsafe.Pointer // Array pointer    len int            // slice length    cap int            // slice capacity} func main() {    array := [20]int{1, 2, 3, 4, 5, 6, 7, 8, 9}    s1 := array[:5]    s2 := append(s1, 10)    s2[0] = 0    // 把slice转换成自定义的 Slice struct    slice1 := (*Slice)(unsafe.Pointer(&s1))    fmt.Printf("ptr:%v len:%v cap:%v \n", slice1.ptr, slice1.len, slice1.cap)    slice2 := (*Slice)(unsafe.Pointer(&s2))    fmt.Printf("ptr:%v len:%v cap:%v \n", slice2.ptr, slice2.len, slice2.cap)}

Output Result:
PTR:0XC04205E0A0 Len:5 cap:20
PTR:0XC04205E0A0 Len:6 cap:20

The result is that the PTR pointer stores the value of the first address in the array, and the two values are the same, so S1 and S2 do point to the same underlying array. However, the elements of these two array slices are different, which can be determined by the first address and the array of slice length len to determine which elements the different array slices should contain, because S1 and S2 point to the same underlying array, but their len is different. Through this demo, it also verifies that the array slicing method is also a value transfer.
3.2 Expansion of array slices:

Run the following code, the difference between thinking and not expanding, and why

func main() {    s1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}    s2 := append(s1, 10)    fmt.Println("s1 =", s1)    fmt.Println("s2 =", s2)    s2[0] = 0    fmt.Println("s1 =", s1)    fmt.Println("s2 =", s2)}

Output Result:
S1 = [1 2 3 4 5 6 7 8 9]
s2 = [1 2 3 4 5 6 7 8 9 10]
S1 = [1 2 3 4 5 6 7 8 9]
S2 = [0 2 3 4 5 6 7 8 9 10]

According to the results we found that after modifying the S2, S1 did not change, this shows that when append (), S1 and S2 do not point to the same underlying array, this is why?

Again, let's run the following code:

  Import ("FMT" "unsafe") type Slice struct {ptr unsafe. Pointer//Array Pointer len Int//Slice length cap int//Slice capacity} Func main () {s 1: = []int{1, 2, 3, 4, 5, 6, 7, 8, 9} s2: = append (S1) fmt. Println ("S1 =", S1) fmt. Println ("s2 =", s2) s2[0] = 0 FMT. Println ("S1 =", S1) fmt. Println ("s2 =", s2)//Convert Slice to a custom Slice struct Slice1: = (*slice) (unsafe. Pointer (&S1)) fmt. Printf ("Ptr:%v len:%v cap:%v \ n", Slice1.ptr, Slice1.len, slice1.cap) Slice2: = (*slice) (unsafe. Pointer (&S2)) fmt. Printf ("Ptr:%v len:%v cap:%v \ n", Slice2.ptr, Slice2.len, Slice2.cap)}  

Output Result:
S1 = [1 2 3 4 5 6 7 8 9]
s2 = [1 2 3 4 5 6 7 8 9 10]
S1 = [1 2 3 4 5 6 7 8 9]
S2 = [0 2 3 4 5 6 7 8 9 10]
ptr:0xc04207a000 Len:9 Cap:9
ptr:0xc04207c000 len:10 cap:18
As the result shows: Append (), S1 and S2 do point to different underlying arrays, and their array capacity caps are not the same. The process is this: when append (), found that the array capacity is not enough, so open up a new array space, the cap becomes twice times the original, S2 point to the new array, so when modifying S2, S1 not affected

Go Language---Slice

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.