Go start: 4, compound type slice array and slice

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

In addition to the basic data types of go, go also supports many composite types of data structures.

Arrays (Array)

An array is a collection of a series of data of the same type.
In the Go language, a type [N]t ] represents an array of values of n T types. Such as:

var a [3]int

Indicates that variable A is declared to have an array with 3 integers. The difference between declarative syntax and Java is that [] is written in front of the type.
Of course, you can also have the compiler count the number of elements in the array literals:

a := [...]int{12,3}

Both, A is an int array that corresponds to a length of 3.
The length of the array is part of its type, so the array cannot change size. The array length can be obtained with the built-in function Len ().

Package Mainimport"FMT"Func main () {vara[2]string//define a string array of length 2    a[0] ="Hello" //subscript 1 assigned to Hello    a[1] ="World"Fmt. Println (a[0],a[1])//Press the subscript valueFmt. Println (a)//print arrayPrimes: = [...] int{2,3,5,7, One, -}//define an int array of length 6 and initialize     forI: =0; I <Len(primes); i++ {fmt. Println (Primes[i])}}


As can be seen from the above, array access and assignment can be subscript, subscript starting from 0, which is consistent with most other programming languages.
The go array also supports multidimensional arrays. This is defined in the following way:

var arrayName [ x ][ y ] variable_type
 PackageMainimport"FMT"Func Main () {A: = [3][4]int{{0,1,2,3}, {4,5,6,7}, {8,9,Ten, One}} FMT. Println (a) forI: =0; I <3; i++ { forJ: =0; J <4; J + + {FMT. Printf ("a[%d[%d] = %d\ n", I, J, A[i][j])}}


The above shows the definition initialization and value of the two-dimensional array.
It is important to note that the last two quotes at the time of initialization cannot be written in a branch, otherwise the go compiler does not know why this restriction is made. The following is an incorrect notation.

a := [3][4    {8, 9, 10, 11}}

Slicing (slice)

As mentioned earlier, the length of the array is immutable, which brings great inconvenience to the operation, but the go gives a good solution, that is, slicing (slice).
The slice of Go is an abstraction of an array. The length of the go array is immutable, and in a particular scenario such a collection is not very suitable, go provides a flexible, powerful built-in type slice ("dynamic array"), compared to the array length is not fixed, you can append elements, may increase the capacity of the slice when appended.

Defined

You can define a slice by declaring an array of unspecified size, type []t represents a slice of the element type T. From this perspective, slices can be considered as arrays of dynamic size.
However, the slice does not store any data, it simply describes a paragraph in the underlying array. Changing the element of a slice modifies the corresponding element in its underlying array. The tiles that share the underlying array with it will observe these changes .

var s []type

In addition, you can use the make () function to create slices:

var slice1 []type = make([]type, length ,capacity)

Where type is the type of slice, length is the initialization length of the slice, capacity is an optional parameter, which refers to the tile capacity.
The Make function assigns an array of zero values to the element and returns a slice that references it.

make([]int, 5)     // len(a)=5, cap(a)=5make([]int, 0, 5)  // len(b)=0, cap(b)=5

The Len () function returns the length of the slice, and the CAP () function returns the tile's capacity.

Initialization

Slice initialization is flexible and there are many ways to do this.
1, the direct initialization of the slice, [] is the slice type, {------------the initialization value is in sequence. its cap=len=3

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

2. Initialize slice s, is a reference to the array arr

s := arr[:] 

3. Create the element in Arr from subscript startindex to endIndex-1 as a new slice, arr can be anarray or it can be a slice, which is the slice that defines the slice that is the slice.

s := arr[startIndex:endIndex] 

4. The default endindex will represent the last element to arr

s := arr[startIndex:] 

5. The default startindex will indicate the start of the first element in arr

s := arr[:endIndex] 

6. Initialize slice s,[]int with built-in function make () to identify slices whose element type is int

s :=make([]int,len,cap
 PackageMainImport "FMT"funcMain () {///1, direct initialization of slices    varS1 = []int{1,2,3,4,5} S11: = []int{1,2,3,4,5}///2, initialize slice s, is a reference to the array arr    vararr = []int{1,2,3,4,5} s2: = arr[:]///3, the element from subscript startindex to EndIndex-1 is created as a new sliceS3: = Arr[1: 3] S31: = S1[1: 3]///4, the default endindex will represent the last element until ArrS4: = arr[3:] S41: = S1[3:]///5, the default startindex will represent the start of the first element in ArrS5: = arr[: 4] S51: = s1[: 4]//6, initialize slice s,[]int with built-in function make () to identify slices whose element type is intS6: = Make([]string,4, -) S6[0] ="a"S6[1] ="B"S6[2] ="C"S6[3] ="D"S61: = Make([]string,4) FMT. Println ("S1:", S1) fmt. Println ("S11:", S11) fmt. Println ("S2:", S2) fmt. Println ("S3:", S3) Fmt. Println ("S31:", S31) fmt. Println ("S4:", S4) Fmt. Println ("S41:", S41) fmt. Println ("S5:", S5) Fmt. Println ("S51:", S51) fmt. Println ("S6:", S6) Fmt. Println ("Len (S6):",Len(S6)) Fmt. Println ("Cap (S6)",Cap(S6)) Fmt. Println ("s61:", s61) fmt. Println ("Len (s61):",Len(S61)) Fmt. Println ("Cap (s61)",Cap(s61))}

The output is:

Empty (nil) slices

The above is for the initialization of the slice, the default is nil before a tile is uninitialized, the length is 0 and there is no underlying array. Nil is a key word for go.

package mainimport"fmt"func main() {    var s []int    lencap(s))    ifnil {        fmt.Println("nil!")    }}


As you can see, the slice s length and capacity are all 0 and the value is nil. That is, the slice is empty.

The inside of the slice

A slice is a description of an array fragment. It contains a pointer to an array, the length of the fragment, and the capacity (the maximum length of the fragment).
The slice operation does not duplicate the element that the slice points to. It creates a new slice and re-uses the underlying array of the original slice. This makes the slice operation as efficient as the array index. Therefore, modifying an element with a new slice affects the corresponding element of the original slice.

"fmt"func main() {    s1 := [...]int{12345}    s2 := s1[2:]    fmt.Println("修改前s1:", s1)    fmt.Println("修改前s2:", s2)    s2[210    fmt.Println("修改后s2:", s2)    fmt.Println("修改后s1:", s1)}

Growth of slices

As I said earlier, slices can be seen as dynamic arrays, so his length is variable. As long as the slice does not exceed the limit of the underlying array, its length is variable, just give it its own slices.

packagemainimport "fmt"funcmain{    s := make([]int, 5, 10)    fmt.Println("修改后s:", len(s))    s = s[:cap(s)]    fmt.Println("修改后s:", len(s))}


Above is to change the length of the slice s to his maximum length. If it exceeds his maximum length, it will be an error-"Panic:runtime Error:slice bounds out of range".

s = s[:12]


If you want to increase the capacity of a slice, we must create a new larger slice and copy the contents of the original Shard. The entire technique is a common implementation that supports dynamic array languages.

 PackageMainImport "FMT"funcMain () {s: = Make([]int,5,Ten) T: = Make([]int,Len(s),Cap(s) * *)//Enlarge the capacity of S     forI: =Ranges {s[i] = i t[i] = s[i]} fmt. Println ("Pre-modification s:", s) fmt. Println ("Before you modify Len (s):",Len(s)) fmt. Println ("Pre-modified cap (s):",Cap(s)) s = T fmt. Println ("Modified s:", s) fmt. Println ("After the modification Len (s):",Len(s)) fmt. Println ("Modified cap (s):",Cap(s))}


It expands the capacity of a slice by twice times.
A copy built-in function is provided for the operations that are copied in the loop. The copy function copies the elements of the source slice to the destination slice. The copy function supports copying between slices of different lengths (it copies only the length of a shorter slice). In addition, the copy function correctly handles overlapping of source and destination slices.
Use the copy function to directly replace the for loop above.

copy(t, s)

In addition to this, go also provides a way to append new elements to the slice –append ().
The first parameter s of append is a slice with the element type T, and the rest of the type T will be appended to the end of the slice. The result of the append is a slice containing all the elements of the original slice plus the newly added elements.

 PackageMainImport "FMT"funcMain () {vars []intFmt. Printf ("len=%d cap=%d%v\n",Len(s),Cap(s), s) s =Append(S,0) FMT. Printf ("len=%d cap=%d%v\n",Len(s),Cap(s), s) s =Append(S,1) FMT. Printf ("len=%d cap=%d%v\n",Len(s),Cap(s), s) s =Append(S,2,3,4) FMT. Printf ("len=%d cap=%d%v\n",Len(s),Cap(s), s) s2: = []int{5,6,7} s =Append(s, s2 ...) Fmt. Printf ("len=%d cap=%d%v\n",Len(s),Cap(s), s)}


The above program creates a nil slice and then continually adds new data to it. s = append (s, s2 ...) The notation is to break back the S2 slices to append, which is the equivalent of S = Append (S, 5, 6, 7), which is also the syntax that go supports.
You can see that the length and capacity of the slices are increasing. By my observation, append increased capacity by multiplying the capacity of the previous slice by 2 if the capacity was not enough, if multiplied by 2 is not enough for the previous capacity +1 multiplied by the number of increments. But this will have to see the source confirmation, today has not found where.

By the current understanding, slices should be used more than arrays in go.

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.