[Golang Study Summary] Slice in the Go language

Source: Internet
Author: User
Tags array definition
This is a creation in Article, where the information may have evolved or changed.

Concept

Slice slicing is the encapsulation of an array of underlying arrays, in memory the essence of storage is an array, reflected as a contiguous block of memory, the go language in the definition of the array, the length is fixed, the use of the process can not change its length, and slice can be seen as a variable length of the array to use, Most crucially, the array is used in the process of value passing, an array is assigned to a new variable or as a method parameter is passed, is the source array in memory completely copied a copy, instead of referencing the source array in memory address, in order to meet the memory space reuse and the value of the array element consistency of application requirements, Slice appears, each slice is a reference to the address of the source array in memory, the source array can be derived from a plurality of Slice,slice can also continue to derive slice, and in memory, always only the source array, of course, there are exceptions, and then again.

Usage

Definition of 1.Slice

Slice can be defined in two ways, one is derived from the source array, one is defined by the Make function, essentially the same, is in memory through the initialization of an array of memory, dividing it into a number of small pieces to store the array elements, The slice then refers to the entire or local array element.

Direct initialization of a slice:

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

Note that this is a little bit different from initializing the array, some students think that this is the definition and initialization of an array, in fact, the writing is now in memory to build an array consisting of 3 elements, and then assign the application of this array to s this slice, by the definition of the following array to differentiate:

A: = [3]int{1, 2, 3}b: = [...] Int{1, 2, 3}c: = []int{1, 2, 3}fmt. Println (Cap (a), Cap (b), Cap (c)) A = Append (A, 4)//error:first argument to append must is slice; has [3]INTB = append (b, 4)//errot:first argument to append must is slice; has [3]INTC = Append (c, 4)//normal, stating that variable C is a slice type

As you can see, the rules of the array definition are emphasized: length and type must be specified, and if the array length is automatically calculated based on the actual number of elements, you need to use [...] Definition, not just [].

To build a slice from a slice in an array:

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}s: = a[2:8]fmt. PRINTLN (s)//output: [3 4 5 6 7 8]

Define an array A, intercept the subscript from 2 to 8 (including 2 excluding 8) and construct a slice.

Defined by the Make function:

S: = make ([]int, Ten,] fmt. PRINTLN (s)//output: [0 0 0 0 0 0 0 0 0 0]
The first parameter of the Make function represents the type of the constructed array, the second parameter is the length of the group, the third parameter is optional, the capacity of the slice, and the default is the second parameter value.

Length and capacity of 2.Slice

Slice has two more confusing concepts, namely length and capacity, what is length? This length is the same as the length of the array, which is the number of elements that have been initialized in memory to actually exist. What is capacity? If you specify a capacity parameter when creating a slice with the Make function, the memory manager divides the memory space by the value of the specified capacity before storing the array elements in it, the extra part is idle, and when the element is appended to the slice, it is first placed in this free memory. If the number of parameters added exceeds the capacity value, the memory manager will re-partition a memory space with a capacity value of the original capacity value, and so on. The benefit of this mechanism is that it can improve computational performance because memory re-partitioning degrades performance.

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}s: = A[0:]s = Append (S, one, $) sa: = a[2:7]sb: = sa[3:5]fmt. Println (A, Len (a), Cap (a))    //output: [1 2 3 4 5 6 7 8 9 0] 10fmt. Println (S, Len (s), Cap (s))    //output: [1 2 3 4 5 6 7 8 9 0 each] 20fmt. Println (SA, Len (sa), Cap (SA))//output: [3 4 5 6 7] 5 8fmt. Println (SB, Len (SB), Cap (SB))//output: [6 7] 2 5

As you can see, the Len and cap of the array are always equal and are specified at the time of definition and cannot be changed. The slice s refers to all elements of this array, with an initial length and capacity of 10, and continues to append 3 elements, and its length becomes 13 capacity of 20. The slice SA intercepts the array fragment labeled 2 to 7, the length is 5, the capacity is 8, and the change rule for the capacity is to subtract the starting subscript from the original capacity value, at which point the appended element overwrites the existing value in the original memory address. Slice SB intercept the array fragment of the slice SA subscript 3 to 5, note that the subscript here refers to the subscript of the SA, not the subscript of the source array, the length is 2, and the capacity is 8-3=5.

3.Slice is a reference type

As mentioned above, slice is a reference to the source array, changing the value of the element in the slice, essentially altering the value of the element of the source array.

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}sa: = A[2:7]sa = append (sa) SB: = sa[3:8]sb[0] = 99fmt. Println (a)  //output: [1 2 3 4 5 7 9 0]fmt. PRINTLN (SA)//output: [3 4 5 7 100]fmt. PRINTLN (SB)//output: [99 7 100 9 0]
As you can see, either the append operation or the assignment operation affects the source array or other elements that reference the slice of the same array. When slice an array reference, it is actually pointing the pointer to the address of the specific element in memory, such as the memory address of the array, in fact the memory address of the first element in the arrays, slice.

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}sa: = a[2:7]sb: = sa[3:8]fmt. Printf ("%p\n", sa)//output: 0XC084004290FMT. Println (&a[2], &sa[0])      //output: 0xc084004290 0xc084004290fmt. Printf ("%p\n", SB)//output: 0XC0840042A8FMT. Println (&a[5], &sb[0])      //output: 0xc0840042a8 0xc0840042a8

4.Slice reference delivery occurs "unexpected"

Above we have been saying that slice is a reference type, pointing to the memory of the same piece of memory, but in the actual application, sometimes there will be an "accident", this situation only occurs when the Append element like a slice, slice processing mechanism is such, When the capacity of the slice is idle, the element that append comes in will directly use the free capacity space, but once the number of elements in the append exceeds the original specified capacity value, the memory manager is to re-open a larger memory space for storing the extra elements, And it will copy the original elements and put them into this newly opened memory space.

A: = []int{1, 2, 3, 4}sa: = a[1:3]fmt. Printf ("%p\n", sa)//output: 0XC0840046E0SA = append (SA, one, $) fmt. Printf ("%p\n", sa)//output: 0xc084003200

You can see that the memory address has changed since the append operation was performed, stating that it is not a reference pass.

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.