"Go Language" "7" Go language slices

Source: Internet
Author: User

If the go language array is a static-length array, then the slice (slice) is a dynamic-length array

First, create slices based on arrays

1, there is an integer array intarr: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, then the following slice is the array slice

var slice []int = Intarr[3:7]

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/5A/02/wKiom1TzEKvQ5lSYAABDmRP4YK8764.jpg "title=" slice. png "alt=" Wkiom1tzekvq5lsyaabdmrp4yk8764.jpg "/>

You can see that the slice starts reading data from the 4th element of the array, up to the 8th element (but not 8th). Remember that the programmer count is from 0 yo 650) this.width=650; "src=" Http://img.baidu.com/hi/face/i_f30.gif "alt=" I_f30.gif "/>


2. What should I do if I read only the first 4 elements of the intarr array? You must be able to think of the smart

var slice [] int = Intarr[0:4]

Or

Slice: = Intarr[0:4]


3. Is there a more concise representation? That's for sure, go knows programmers.

Slice: = Intarr[:4], which is equivalent to slice: = Intarr[0:4]


4, which read all the data after the 4th element of the Intarr array (containing the 4th element)?

Slice: = Intarr[3:10]

Of course, you can also say the following

Slice: = Intarr[3:len (intarr)]

Or

Slice: = intarr[3:]


Second, the relationship between the slice created by the array and the array

In the example above, we created the slice slice based on the array intarr, so what does slice have to do with intarr? It can be simply understood that the slice is based on an array that adds some administrative functionality, and the very type of array in C + + is related to std::vector.

Intarr: = [10]int{1,2,3,4,5,6,7,8,9,10} //define array Intarr

var slice []int = Intarr[3:7] //create slices based on intarr


Fmt. Printf ("Intarr's address is:%p\n", &intarr)

Fmt. Printf ("Slice's address is:%p\n", &slice)


Fmt. Printf ("The 4th element of the Intarr address is:%p\n", &intarr[3])

FMT. Printf ("The 1th element of the slice address is:%p\n", &slice[0])650) this.width=650; src= http://s3.51cto.com/wyfs02/M01/5A/0B/ Wkiom1t0vy7qgnb7aanzonkibnu543.jpg the relationship of the "title=" slice to the array. png "alt=" wkiom1t0vy7qgnb7aanzonkibnu543.jpg "/>

From the running results of the program you can see that the slices slice and arrays intarr have no relation to each other and are different intrinsic addresses; But interestingly, the first element of the slice slice is the address of the 4th element of the array intarr, which is not a coincidence, but the essence of the slice.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5A/0B/wKiom1T0agKDLE86AADJOhQDpwA427.jpg "title=" The relationship between slices and arrays 2.png "alt=" Wkiom1t0agkdle86aadjohqdpwa427.jpg "/>

So some people also say that slices are pointers to arrays, and changes to the slice elements affect the values of the array elements, which can be verified by overwriting the above example:

Intarr: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Slice: = intarr[3:]

Slice[0] = +//Change the 1th element value of the slice to

Fmt. Println ("slice=", Slice)

Fmt. Println ("intarr=", Intarr)

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/0B/wKiom1T0awuBcatWAABUvGIMtF0935.jpg "title=" Object passed. png "alt=" wkiom1t0awubcatwaabuvgimtf0935.jpg "/>


Creating slices based on slices

Can I create slices based on slices? The answer is yes, it uses the same method as creating slices based on arrays

Intarr: = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Slice: = intarr[3:]

Reslice: = slice[1:]

Fmt. Println (Reslice)

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5A/12/wKioL1T1oObxjV1yAAAmMpP3f9I678.jpg "title=" Slice the slice. png "alt=" wkiol1t1oobxjv1yaaammpp3f9i678.jpg "/>

Since slice is a slice created from an array intarr, it starts with the 4th value of Intarr, so the value of slice is [4,5,6,7,8,9,10], and Reslice is a slice created based on the slice slice, which starts with the 2nd value of slice, So the value of Reslice is [5,6,7,8,9,10]


Iv. creating slices directly

Instead of having to create slices based on arrays or slices, the go language is a thoughtful way for programmers to provide the make () function in the form slice: = make ([] type, number, capacity), for example:

Slice: = Make ([]int, 3, 10)

1. What is the meaning of number and capacity respectively?

number is a slice element, after creating a slice slice, there are several elements; capacity represents the capacity of the slice, and after the slice slice is created, the storage space for 10 elements is reserved. Run the above example to understand:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/12/wKioL1T1pQPSLsJfAABYae7tmek339.jpg "title=" Make slice. png "alt=" wkiol1t1pqpslsjfaabyae7tmek339.jpg "/>

From the results, the number of slices slice elements is 3, and the element default padding is 0, because the slice slice capacity is 10, so you can also append 7 elements to the slice.


2, Len () and Cap ()

The slices have the Len () and Cap () functions, which are used to obtain the number of elements and the capacity values of the slices, for example:

Slice: = Make ([]int, 3, 10)

Num: = Len (slice)

Capacity: = Cap (slice)

Fmt. Println ("Number of slices slice elements:", num, ", Capacity:", capacity)

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5A/16/wKiom1T1pZyhU9tVAABCLSlHOTc784.jpg "title=" Number of slices and capacity. png "alt=" wkiom1t1pzyhu9tvaabclslhotc784.jpg "/>


3, can omit the capacity?

The answer is OK, so you can declare the slice like this: slice: = make ([]int,3)

At this point it has the same capacity as the number of elements, which is 3


4, can the number of elements and capacity are omitted into slice: = make ([]int) feasible?

The answer is no, at this point the go language dizzy, it is thinking that the programmer let me put all the memory occupied? Throws missing Len argument to make ([]int) error message


5, only type and capacity, omit the number of elements, similar to slice: = make ([]int,,10)

The answer is NO650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0081.gif "alt=" J_0081.gif "/>", but can be declared after direct initialization, i.e. slice: = []int{1,2,3,4,5,6}650] this.width=650; "src=" Http://img.baidu.com/hi/youa/y_0003.gif "alt=" Y_0003.gif "/>


6, how to add elements?

Slice: = Make ([]int, 3, 10)

Fmt. Println ("Number of slices slice elements:", Len (Slice), ", Capacity:", cap (Slice), ", slice=", slice)

You can append this:

Slice = Append (slice, 4)

Slice = Append (slice, 5)

You can also append this:

Slice = append (slice, 6, 7, 8)

You can even append a slice, but you must add it later ... :

Arr: = [2]int{9, 10}

Slice = append (slice, arr ...)

After the program runs, the result is as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/16/wKiom1T1qsjCox0EAAMP71W_5V0528.jpg "title=" Slice append. png "alt=" wkiom1t1qsjcox0eaamp71w_5v0528.jpg "/>


Does the slice regenerate after the slice appends the element?

1. Additional Instructions

Slice: = Make ([]int, 3, Ten) //Declare a slice

Fmt. Printf ("Address of original Slice%p\n", &slice)

Fmt. Printf ("Address of the first element of the original slice%p\n", &slice[0])


Slice = Append (slice, 4) //Append an element

Fmt. Printf ("Address of new slice%p\n", &slice)

Fmt. Printf ("Address of the first element of the new slice%p\n", &slice[0])

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5A/16/wKiom1T1r7PDJAjOAACdEk52urY469.jpg "title=" The slice is appended with the address. png "alt=" wkiom1t1r7pdjajoaacdek52ury469.jpg "/>

As you can see from the running results, the address of the slice element does not change after appending an element, but must return a value to slice when applied, that is, the following program is wrong:

Slice: = Make ([]int, 3, 10)

Append (Slice, 4)//Must return slice

Fmt. Printf ("%p\n", &slice)


2, append more than the capacity size

Slice: = Make ([]int, 3, Ten) //Slice capacity is ten

Fmt. Printf ("%p\n", &slice) //print slice address

Fmt. Println ("Len:", Len (Slice), "cap:", cap (slice)) //print the number of slice elements and capacity


Slice = Append (Slice, 4, 5, 6, 7, 8, 9, ten, one) //slice append element

Fmt. Printf ("%p\n", &slice) //print slice address

Fmt. Println ("Len:", Len (Slice), "cap:", cap (slice)) //print the number of slice elements and capacity

In this example, a slice with a capacity of 10 is declared at the beginning, and when an element is appended to the slice, the number of elements exceeds the capacity, and the slice automatically expands capacity one time to 20, which is similar to the Java collection
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/16/wKiom1T1rgrCXhDwAALhkil8MXE502.jpg "title=" Slice extension. png "alt=" wkiom1t1rgrcxhdwaalhkil8mxe502.jpg "/>

This article is from the "Green Guest" blog, please be sure to keep this source http://qingkechina.blog.51cto.com/5552198/1616987

"Go Language" "7" Go language slices

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.