A summary of slice learning in go language _golang

Source: Internet
Author: User
Tags array length

Concept

A slice slice is an encapsulation of an array of underlying arrays, in memory the essence of storage is an array, which is embodied as a contiguous block of memory, after the definition of the array in the go, the length is fixed, the length is not changed in the course of use, and slice can be regarded as a variable length array for use, The most critical is that the array is used in the process of value transfer, when an array is assigned to a new variable or passed as a method parameter, the source array is completely copied in memory rather than the address in memory of the source array, in order to satisfy the application requirements of the consistency of the values of the reuse and arrays of memory space. Slice appears, each slice is a reference to the address of the source array in memory, the source array can be derived from multiple Slice,slice can also continue to derive slice, while in memory, always only the source array, of course, there are exceptions, and then say.

Usage

Definition of 1.Slice

Slice can be defined in two ways, one is derived from the source array, the other is defined by the Make function, essentially the same, is in memory through the initialization of the array of memory, divided into several small blocks to store the array elements, Slice then refers to the entire or local array element.
Direct initialization of a slice:

Copy Code code as follows:

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

Note that this is a little bit different from initializing the array, some students think this is a definition and initialization of an array, in fact this is now in memory to build a 3-element array, and then the application of the array to the slice, the definition of the following array to distinguish:

Copy Code code as follows:

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; have [3]int
b = Append (b, 4)//errot:first argument to append must is slice; have [3]int
c = Append (c, 4)//normal, indicating that variable C is slice type

As you can see, the rules for array definitions are highlighted: length and type must be specified, and if the array length is automatically calculated based on the number of actual elements, you need to use [...] Definition, and you cannot use only [].

To build a slice from a slice in an array:

Copy Code code as follows:

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 2 to 8 portion (including 2 excluding 8), and construct a slice.

Defined by the Make function:

Copy Code code as follows:

S: = make ([]int, 10, 20)
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 is optional, the capacity of the slice, and the second parameter value by default.

Length and capacity of 2.Slice

Slice has two more confusing concepts: length and capacity, what is length? This length is a concept of the length of an array, that is, the number of actual elements that are initialized in memory. What is capacity? If you specify a capacity parameter when creating slice through the Make function, the memory manager divides a chunk of memory according to the value of the specified capacity, then stores the array elements in it, the extra part is idle, and when the element is appended to the slice, it is first placed in the spare memory. If the number of parameters added exceeds the capacity value, the memory manager divides the memory space with a capacity value of the original capacity value *2 size, and so on. The advantage of this mechanism is that it can improve operational performance, since the redistribution of memory can degrade performance.

Copy Code code as follows:

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
S: = a[0:]
s = Append (S, 11, 22, 33)
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] 10 10
Fmt. Println (S, Len (s), Cap (s))//output: [1 2 3 4 5 6 7 8 9 0 11 22 33] 13 20
Fmt. Println (SA, Len (sa), Cap (SA))//output: [3 4 5 6 7] 5 8
Fmt. 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 the array, the initial length and capacity are 10, and the length of the 3 elements is changed to 13 capacity 20. The slice SA intercepts the array fragment of subscript 2 through 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 Append element will overwrite the value existing in the original memory address. Slicing SB to intercept an array fragment of the slice SA subscript 3 to 5, note that the subscript here refers to the SA subscript, not the subscript for 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 changing the value of the element in the source array.

Copy Code code as follows:

A: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
SA: = A[2:7]
SA = append (sa, 100)
SB: = Sa[3:8]
SB[0] = 99
Fmt. Println (a)//output: [1 2 3 4 5 99 7 100 9 0]
Fmt. PRINTLN (SA)//output: [3 4 5 99 7 100]
Fmt. PRINTLN (SB)//output: [99 7 100 9 0]

As you can see, both the append operation and the assignment operation affect the source array or other elements referencing the slice of the same array. When slice an array reference, it is actually pointing the pointer at the address of the specific element in memory, such as the memory address of the group, which is in fact the memory address of the first element in the array, slice.

Copy Code code as follows:

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: 0xc084004290
Fmt. Println (&a[2], &sa[0])//output: 0xc084004290 0xc084004290
Fmt. Printf ("%p\n", SB)//output: 0xc0840042a8
Fmt. Println (&a[5], &sb[0])//output: 0xc0840042a8 0xc0840042a8

4.Slice reference delivery occurred "unexpected"

Above we have been saying that slice is a reference type, pointing to the same memory in memory, but in practical applications, sometimes there will be "unexpected", this situation only in the case of append elements like slicing, slice processing mechanism is this, When the slice capacity is idle, the APPEND elements will use the free capacity space directly, but once the number of elements in the append exceeds the original specified capacity value, the memory manager is to reopen a larger memory space for storing the extra elements, And it will copy the original elements into the new memory space.

Copy Code code as follows:

A: = []int{1, 2, 3, 4}
SA: = A[1:3]
Fmt. Printf ("%p\n", sa)//output: 0XC0840046E0
SA = append (SA, 11, 22, 33)
Fmt. Printf ("%p\n", sa)//output: 0xc084003200

You can see that the memory address has changed since the append operation was performed, indicating 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.