Go Language Practical Notes (iv) | Go Array

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

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.

arrays, which are used to store collections of data, are very numerous, and in the process of encoding, we have to read or store the data. Of course, in addition to arrays, we also have data structures such as slices, map maps, and so on that can help us store the information, but arrays are the basis for them.

Internal implementation

To understand the array more clearly, we need to understand its internal implementation. Arrays are fixed-length data types and must store elements of the same type, and these elements are contiguous. We emphasize the fixed length here, which can be said to be the most obvious difference from the slice.

The type of array storage can be a built-in type, such as an integer or a string, or it can be a custom data structure. Because it is continuous, the index is computationally good, so we can quickly index any data in the array.

The index here has always been 0,1,2,3, because its element type is the same, we can also use reflection, get the type occupies the size, carry on the shift, get the corresponding element, this reflection, we say again.

Declaration and initialization

The Declaration and initialization of an array is similar to other types. The principles of the Declaration are:

    1. Indicates the type of data stored.
    2. The number of stored elements, that is, the array length.
var array [5]int

We have declared an array above, array but we have not initialized it yet, when the value in the array array is 0 values of the corresponding element type, that is, the array is now 5 0, which is not the same as ours, Java is null.

Once an array is declared, its element type and size cannot be changed, but what if more elements need to be stored? Then you can only copy the data from the original array by creating a new array.

The array you just declared has been initialized with the default element type 0 value, and if we do this again, we can use the following method:

var array [5]intarray = [5]int{1,2,3,4,5}

These two steps are tedious, and go gives us an := operator that allows us to initialize the array directly when we create it.

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

This short variable declaration is not only suitable for arrays, but also for any data type, which is a common way in the go language.

Sometimes we are more lazy, even the length of the array does not want to specify, but it does not matter, the use of ... substitution is good, go will automatically deduce the length of the group.

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

If we just want to initialize the corresponding values for an array indexed to 1 and 3, the others are 0 how to do it, the direct way is:

array:=[5]int{0,1,0,4,0}

There is a better way of saying that the default is initialized to a value of 0, then we can use this feature to initialize only the values of indexes 1 and 3:

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

Working with arrays

The access to the array is very simple, by index, by the operator [] , because the memory is contiguous, so the efficiency of index access is very high.

array:=[5]int{1:1,3:4}fmt.Printf("%d",array[1])

It is also simple to modify an element in an array:

array:=[5]int{1:1,3:4}fmt.Printf("%d\n",array[1])array[1] = 3fmt.Printf("%d\n",array[1])

If we want to loop through all the values in the print group, a traditional for loop is a common one:

func main() {    array := [5]int{1: 1, 3: 4}    for i := 0; i < 5; i++ {        fmt.Printf("索引:%d,值:%d\n", i, array[i])    }}

Most of the time, however, we use the For Rang loop:

func main() {    array := [5]int{1: 1, 3: 4}    for i, v := range array {        fmt.Printf("索引:%d,值:%d\n", i, v)    }}

These two sample codes output the same result.

Arrays of the same type can be assigned to each other, different types of not, and compile errors. So what is the same type of array? The go language rules must be the same length, and each element has the same type of array, which is the same type of array.

array := [5]int{1: 1, 3: 4}var array1 [5]int = array //successvar array2 [4]int = array1 //error

The array of pointers and arrays itself is similar, except that the element type is a pointer.

array := [5]*int{1: new(int), 3:new(int)}

This creates a pointer array and creates a memory space for both the index 1 and 3, and the other index is the 0 value of the pointer, and it is nil also simple to modify the value of the pointer variable, as follows:

array := [5]*int{1: new(int), 3:new(int)}*array[1] = 1

It is important to note that only indexes 1 and 3 can be assigned, because only they allocate memory, it can be assigned, if we assign to index 0, run, will prompt invalid memory or a nil pointer reference.

panic: runtime error: invalid memory address or nil pointer dereference

To solve this problem, we need to allocate the memory to index 0 before making the assignment modification.

array := [5]*int{1: new(int), 3:new(int)}array[0] =new(int)*array[0] = 2fmt.Println(*array[0])

Passing arrays between functions

When passing variables between functions, always in the way of values, if the variables are arrays, then the entire copy, and passed to the function, if the array is very large, such as the length of more than 1 million, then this memory is a significant overhead.

func main() {    array := [5]int{1: 2, 3:4}    modify(array)    fmt.Println(array)}func modify(a [5]int){    a[1] =3    fmt.Println(a)}

From the above example, you can see that the array is copied and the original array is not modified. We here are 5-length arrays Okay, if there is millions of, one way is to pass the pointer to the array, so that the size of the copy is just an array type of pointer size.

func main() {    array := [5]int{1: 2, 3:4}    modify(&array)    fmt.Println(array)}func modify(a *[5]int){    a[1] =3    fmt.Println(*a)}

This is an example of passing an array of pointers, and it will be found that the array has been modified. So this situation saves the memory of replication, but it should be used sparingly, because accidentally, the original array will be modified, causing unnecessary problems.

Note here that array pointers and pointer arrays are two concepts, the pointer to an array is *[5]int , the pointer array is [5]*int , * the position of attention.

For the problem of passing arrays between functions, such as replication problems, such as the size of the problem, there are better solutions, this is the slice, it is more flexible, next we will detail.

"Go language Combat" reading notes, not yet to be continued, welcome to sweep code attention to the public number flysnow_org , the first time to see follow-up notes.

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.