Go Learning record (ii)---array and array slices

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

In the Go language learning, there is no contact with arrays and array slices, and the use of both is very frequent. So if you don't get a good understanding, it may be easy to make mistakes. So in go, arrays and array of slices have what characteristics, and how to declare the assignment, how to use it, the following I have a summary of their own, personal summary may not be complete or wrong, hope pointing.

The characteristics of arrays and groups of slices

The array is nothing to say, as a developer, this is often used in things, I believe we all have their own understanding. Now let's summarize the features of the array.

1. The length of the array cannot be changed after it is defined

2. The length of an array declaration must be a constant or constant expression, that is, the length can be determined in the compiler, allocating memory

3. The subscript of the array starts at 0 and the last element is labeled (length-1), which can be written as Len (arr) in Go-1

4. The go language array is a value type that is copied as an array when passed as a parameter. Therefore, when passed as a parameter, the modified content does not affect the original array content, only the copy within the passed function is affected.

Array slicing: is a new type of data that go provides, and its use in the go language has the effect of pointers in C or C + +. However, because it is different from pointers, there is no pointer operation for languages in C or C + +. The bottom layer of an array slice is implemented by an array, which is easy to associate with C + + vectors.

1. Unlike arrays, the length of an array slice is variable, meaning that memory space can be allocated dynamically. However, the current element is replicated once each time a new space is allocated

2. The go language provides built-in function copy to copy content from one array slice to another array slice, but if the length of the two array slices is different, the number of smaller array slices is copied.

3. Array slices are the same as arrays, their subscripts start at 0, the last element is labeled (length-1), which can be written as Len (arr) in Go-1

4. The go language provides a cap () built-in function to get the amount of space allocated to an array slice, which may be returned in a different size than Len ()

5. Array slices provide the specified length and reserved storage space at creation time. When you know how long an array slice will last, you can avoid the request release and replication of memory that is caused by tile expansion.

6. When an array slice is passed as a parameter, there is no memory copy operation, and if the parameters of the incoming slice are modified in the function, the contents of the original array slice can be modified directly.

Second, array and array slicing use

(i) Declaration and creation

The definition initialization of an array is simple, as follows:

1. var arr [10]int//declares a length of 10, an array of type int. You can also declare multidimensional arrays, such as: Var Twod [10][100]int. You can also define arrays of complex types, such as: Var St_arr [100]struct {x, y int}

ARR[1] = 1 //Assign value according to index

2. arr: = [5]int{1,2,3,4,5}//Declare and initialize the array

3. var arr [5]int = [5]int{1,2,3,4,5}//define and initialize array

The definition and initialization of array slices are as follows:

1. Array-based creation

Arr: = [10]int{1,2,3,4,5}

var Slc1 []int = arr[:]//create slices based on all elements of the array

var slc2 []int = Arr[:5]//create slices based on first five elements

var slc3 []int = arr[5:]//Based on creation of slices from Fifth Element

var slc4 []int = Arr[2:8]//Based on creation of slices from second to eighth elements

The above several ways to create slices are based on the creation of a rule: Create an array slice in this way based on Arr[first:last]

2. Create directly

Slice1: = Make ([]int, 5)//Create an array slice with an initial element number of 5 and an element with an initial value of 0

Slice2: = Make ([]int, 5, +)//Create an array slice with an initial element number of 5, an element with an initial value of 0, and reserve a storage space of 10 elements

Slice3: = []int{1, 2, 3, 4, 5}//Create and initialize array slices with 5 elements directly

3. Creating an array slice based on an array slice

Creating an array slice based on an array slice is basically the same as creating a slice based on an array. However, the number of newly created slice elements can exceed the number of elements contained in the old slice, which requires that the number of elements in the newly created slice not exceed the capacity of the old slice. Such as:

Slice1: = Make ([]int, 5, 10)

Slice2: = Slice1[:6]


(ii) Traversing elements

In go, both arrays and array slices provide two identical traversal methods:

1. Use traditional for traversal:

For I: = 0; I < Len (arr); i++ {

Fmt. Println ("arr[", I, "] is", Arr[i])

}

2. Use the Range keyword:

For I, V: = Range arr {

Fmt. Println ("arr[", I, "] is", V)

}


(iii) Length acquisition

For arrays and array slices, the go language provides built-in function Len (), using the Way Len (arr), to return the length of the current array or array slices. For array slices, the go language provides built-in function cap () to get the capacity of an array slice

(iv) Adding elements

For array length, there is no function to add elements. But array tiles can provide an append element because of the dynamic memory problem. A built-in function is provided in the Go language append as an element of an array slice. There are two ways to use this:

1. Adding elements directly:

Slice1: = []int{1,2,3,4}

Slice1 = Append (Slice1, 5, 6, 7)//Append the first parameter is based on the array slice. The second argument is an indeterminate argument, and multiple elements can be appended

2. Array slices append array slices:

Slice1: = []int{1,2,3,4}

Slice2: = []int{5,6,7,8}

Slice1: = Append (Slice1, Slice2 ...) //Special note here: You need to add three points after the second array slice, or you will compile an error. The main reason is that the second parameter of append is the element to be appended, and the effect of adding three points is to pass the elements of the slice2 into the element content list instead of passing in as a slice as a parameter.


(v) passing as a parameter

1. Arrays as parameters

Func sort (arr [ten] int) {

...

}

The call to this function is as follows:

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

ARR2: = [5]int{4,2,3,5,1}

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

Sort (arr) //compile normally, but since array-pass is a value parameter, the array is copied at the time of the parameter, so only the value of arr within sort is modified, and the actual element value content of ARR1 is not modified

Sort (arr2) //Compile error, for Go, [10]int and [5]int are two different data types

Sort (&arr) //Compile error, for C or C + +, the function parameter is defined as int arr[10] This is actually a pointer that defines an array to pass in. But in the go language, array pointers and arrays are two completely different types

Sort (Slice1)//compile errors, also because of different types

2. Array slices as parameters

Func sort (arr []int) {

...

}

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

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

Sort (arr)//Compilation error, type different

Sort (Slice1)//compiles correctly, and changes to slice in sort are modified directly to the original slice.

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.