Go Learning notes: arrays

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
    • An array is a group of elements that have an 相同数据类型 element 固定长度 有序集合 .

    • In the go language, arrays are value types, and lengths are part of a type, meaning " [10]int and" [20]int are two completely different types of arrays.

    • Two arrays of the same type support a comparison of "= =" and "! =", but cannot compare size.

    • Array as a parameter, the inside of the function does not change the value inside the array unless it is a pointer to the incoming array.

    • Pointers to arrays: *[3]int

    • Array of pointers: [2]*int


Example 1:

package mainimport  "FMT" Func main ()  {    //  Here we have created an array of integers with 5 elements The data type and array length of the     //  element are part of the arrays     //  by default, array elements are 0 values      //  for integers, the value of 0 is 0    var a [5]int    fmt. Println ("EMP:",  a)     //  We can use an index to set the value of an array element, like this     //  " Array[index] = value "   or use an index to get the element value,    //  like this" Array[index "     a[4] = 100    fmt. Println ("Set:",  a)     fmt. Println ("Get:",  a[4])     //  The built-in Len function returns the length of the array     fmt. Println ("Len:",  len (a))     //  This method can define and initialize an array     b&nbsp at the same time;: = [5]int{1, 2, 3, 4, 5}    fmt. Println ("DCL:",  b) &NBSP;&NBSP;&NBSP;&NBSP;//&NThe array is one-dimensional, but you can define the elements of the array as an array     //  to get the multidimensional array structure &NBSP;&NBSP;&NBSP;&NBSP;VAR&NBSP;TWOD  [2][3]int    for i := 0; i < 2; i++ {         for j := 0; j < 3; j++  {            twod[i][j] = i +  j        }    }    fmt. Println ("2d: ",  twod)}

The output result is

EMP: [0 0 0 0 0]set: [0 0 0 0 100]GET:100LEN:5DCL: [1 2 3 4 5]2d: [[0] 1 2] [1 2 3]]

拥有固定长度is a feature of the array, but this feature can sometimes cause a lot of inconvenience, especially if the number of elements in a set is not fixed. This time we use more 切片 .


Example 2:

You can create an array with new and return a pointer to the array

Package Mainimport "FMT" Func Main () {var a = new ([5]int) test (a) fmt. Println (A, Len (a))}func test (a *[5]int) {a[1] = 5}

Output results

&[0 5 0 0 0] 5


Example 3:

Package Mainimport "FMT" Func Main () {a: = [...] user{{0, "User0"}, {8, "User8"},} B: = [...] *user{{0, "User0"}, {8, "User8"},} FMT. Println (A, Len (a)) fmt. Println (b, Len (b))}type User struct {Id int Name string}

Output results

[{0 User0} {8 User8}] 2[0x1f216130 0x1f216140] 2


Example 4 (exercise):

package main import  (         "FMT")  func main ()  {         var arr_1 [10]int         var sum int         fmt. Println ("\nlen (arr_1): ",  len (arr_1))         fmt. Println ("initial value of arr_1:")         for _,  elem := range arr_1 {                 fmt. Print (elem,  " ")         }         fmt. Println ("\ninitial value of sum: ", sum,  "\ n")           fmt. Println ("arr_1:")          for i := 0; i < len (arr_1); i++ {                 arr_1[i] = len (arr_1)  -  1 - i                 fmt. Println (Arr_1[i])         }          fmt. Println ("\neach set of range arr_1:\nidx val\n-------")          for idx, val := range arr_1 {                 fmt. Println (Idx, val)         }          for _, elem := range arr_1 {                 sum += elem        }          fmt. Print ("\nsum of arr_1: ", sum,  "\ n")           // define array with length unknown, must initialize when  defining        var arr_2 = [...] string{                 "Sun",                  "Air",                  "Water"}         fmt. Println ("arr_2:")         for _, elem := range  arr_2 {       &nbsP;        fmt. Println (Elem)         }          fmt. Println ()}

Output results

Len (arr_1): 10initial value of arr_1:0 0 0 0 0 0 0 0 0 0 Initial value of sum:0 Arr_1:9876543210each set of range arr_1 : idx val-------0 approx. 0sum of Arr_1:45arr_2:sunairwater


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.