Go Language Summary (3)--arrays and slices

Source: Internet
Author: User

The previous post briefly introduced the basic type of Go language--go language Summary (2)-basic type, this post begins to introduce the go language arrays and slices.

One, array

Like most other languages, the Go Language array is also a fixed-length sequence with the same element type.

(1) Creation of arrays.

There are 3 ways to create arrays:[Length]type ,[N]type{value1, value2, ..., valuen},[...] Type{value1, value2, ..., Valuen} are as follows:

func test5 () {varIarray1 [5]int32varIarray2 [5]int32 = [5]int32{1,2,3,4,5} iarray3:= [5]int32{1,2,3,4,5} iarray4:= [5]int32{6,7,8,9,Ten} iarray5:= [...] int32{ One, A, -, -, the} iarray6:= [4][4]int32{{1}, {1,2}, {1,2,3}} fmt. Println (iarray1) fmt. Println (iarray2) fmt. Println (IARRAY3) fmt. Println (IARRAY4) fmt. Println (Iarray5) fmt. Println (IARRAY6)}

Results:

[0 0 0 0 0][1 2 3 4 5][1 2 3 4 5][6 7 8 9 Ten][ One  A  -  -  the][[1 0 0 0] [1 2 0 0] [1 2 3 0] [0 0 0 0]]

We looked at the array iarray1, only declared, not assigned, and C helped us to automatically assign a value of 0. Looking again at Iarray2 and Iarray3, we can see that the go Language Declaration, can indicate the type, can also not indicate the type, var iarray3 = [5]int32{1, 2, 3, 4, 5} is also completely no problem.

(2) The capacity and length of the array are the same. Both the CAP () function and the Len () function output the capacity (that is, the length) of the array. Such as:

func Test6 () {    iarray4:= [5]int32{6789 }    FMT. Println (Len (iarray4))    FMT. Println (Cap (IARRAY4))}

The output is all 5.

(3) Use:

func test7 () {    iarray7:= [5]string{"aaa" "  Yes, "" tell me what to say . ""()"}    Fmt. Println (iarray7)    for i: = range Iarray7 {        fmt. Println (Iarray7[i])    }}

Output:

func test7 () {    iarray7:= [5]string{"aaa" "  Yes, "" tell me what to say . ""()"}    Fmt. Println (iarray7)    for i: = range Iarray7 {        fmt. Println (Iarray7[i])    }}

Second, slicing

In the go language, slices are the same sequence of elements with variable lengths and fixed capacity. The slice nature of the go language is an array. The capacity is fixed because the length of the array is fixed, and the slice's capacity is the length of the hidden array. Variable length refers to the variable in the range of the array length.

(1) Creation of slices.

There are 4 ways to create slices:

1) make ([]type, length, capacity)

2) make ([]type, length)

3) []type{}

4) []type{value1, value2, ..., Valuen}

From 3), 4), the only difference between creating a slice and creating an array is whether there is a number in the "[]" before Type, or a slice if it is empty, otherwise it represents the array. Because the slices are variable in length. Here's an example of creating a slice:

func test8 () {    Slice1:58)    slice2:9)    slice3:= []int32{}    slice4:= []int32{12345}    FMT. Println (Slice1)    FMT. Println (SLICE2)    FMT. Println (slice3)    FMT. Println (Slice4)}

The output is:

[00000]00000  0000][][12 3  45]

As above, created 4 slices, 3 empty slices, and one valued slice.

(2) slices and hidden arrays:

A slice is a reference to a hidden array, and a slice of that slice also references the same array. The following example creates a slice slice0 and creates 2 slices of slice1 and slice2 based on the slice:

func Test9 () {slice0:= []string{"a","b","C","D","e"} Slice1:= slice0[2: Len (SLICE0)-1] Slice2:= slice0[:3] FMT. Println (Slice0, Slice1, Slice2) slice2[2] ="8"FMT. Println (Slice0, Slice1, Slice2)}

The output is:

8 d e] [88]

As you can see, slices slice0, Slice1, and Slice2 are references to the same underlying array, so SLICE2 changes and the other two change.

(3) Traversing and modifying slices:

func test10 () {slice0:= []string{"a","b","C","D","e"} fmt. Println ("\n~~~~~~ element Traversal ~~~~~~")     for_, Ele: =range Slice0 {fmt. Print (Ele," ") Ele="7"} fmt. Println ("\n~~~~~~ Index Traversal ~~~~~~")     forIndex: =range Slice0 {fmt. Print (Slice0[index]," ")} FMT. Println ("\n~~~~~~ Element Index common use ~~~~~~")     forIndex, Ele: =range Slice0 {fmt. Print (Ele, Slice0[index]," ")} FMT. Println ("\n~~~~~~ modifying ~~~~~~")     forIndex: =range Slice0 {Slice0[index]="9"} fmt. Println (SLICE0)}

As above, the first three loops use a different for Range loop, when the for followed, the range has 2 elements in front of it, the element represents the index, the second element represents the value of the element, and "_" is ignored because the unused value in the Go language causes a compilation error.

When there is only one element, the element represents the index.

You can modify an element only by using an index. As in the first traversal, the assignment ele is 7, and the result has no effect. Because Ele is a value pass in an element traversal, Ele is a copy of the slice element, and modifying it does not affect the original value, but in the fourth traversal-the index traversal, the value referenced by the slice element is modified, so it can be modified.

The result is:

~~~~~~ element Traversal ~~~~~~~~~~~~ index traversal ~~~~~~~~~~~~ Element Index common use ~~~~~~~~~~~~ Modify ~~~~~~[9  9999]

(4), Append, copy slices:

func test11 () {slice:=[]int32{} fmt. Printf ("the length of the slice is:%d,slice:%v\n", Len (slice), slice) slice= Append (Slice, A, One,Ten,9) fmt. Printf ("after appending, the length of the slice is:%d,slice:%v\n", Len (slice), slice) SLICECP:=Make ([]int32, (Len (slice))) fmt. Printf ("the length of the SLICECP is:%D,SLICECP:%v\n", Len (SLICECP), SLICECP) copy (SLICECP, slice) fmt. Printf ("after the assignment is copied, the length of the SLICECP is:%D,SLICECP:%v\n", Len (SLICECP), SLICECP)}

Append, copy slices, with built-in functions append and copy,copy functions return the number of elements that were last copied.

(5), built-in function append

Built-in function append you can append one or more other values of the same type to a slice. If the number of elements appended exceeds the original slice capacity, then the last returned is a new slice in a completely new array. If not, the last returned is a new slice in the original array. In any case, the append has no effect on the original slice. The following example:

func test12 () {slice:= []int32{1,2,3,4,5,6} slice2:= slice[:2]    _ = Append (Slice2, -, -, -, the, -) fmt. Printf ("Slice is:%v\n", Slice) fmt. Printf ("Slice of operation:%v\n", Slice2) _= Append (Slice2, -, -) fmt. Printf ("Slice is:%v\n", Slice) fmt. Printf ("Slice of operation:%v\n", Slice2)}

As above, the Append method was used 2 times, resulting in a completely different result because the number of elements appended to the second Append method did not exceed the capacity of slice. In any case, the original slice slice2 has no effect. Results:

Slice: [123456] operation of the slice: [12] Slice: [1256] slices of operation: [ 1 2]

Go Language Summary (3)--arrays and 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.