Go basic--03 (array, slice, map)

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

Study Notes

1. ArrayAn array is a pattern that is defined as follows: var arr [N]typein [N]type, n represents the length of the array, and type represents the types of the stored elements. Operations of an array are similar to other languages, and are read or assigned by []:
var arr [10]int//declares an array of type int
ARR[0] = 42//array subscript is starting from 0
ARR[1] = 13//Assignment operation
Fmt. Printf ("The first element is%d\n", arr[0])//Get data, return 42
Fmt. Printf ("The last element is%d\n", arr[9])//Returns the final element that is not assigned, returns 0 by default
Because length is also part of the array typeSo [3]int and [4]int are different types, the array cannot change the length. The assignment between the arrays is values are assigned, that is, when an array is passed into the function as a parameter, it is actually the copy of Array, while not a pointer to it. If you are using pointers, you need to use the following Slice TypeThe An array can use another: = To declare
A: = [3]int{1, 2, 3}//declares an int array of length 3
B: = [10]int{1, 2, 3}//declares an int array of length 10, where the first three elements are initialized to 1, 2, 3, others default to 0
c: = [...] Int{4, 5, 6}//Can omit length and adopt ' ... ' way, go will automatically calculate the length based on the number of elements
Perhaps you would say, I think the array inside the value or array, can it be implemented? Of course, go supports nested arrays, or multidimensional arrays. For example, the following code declares a two-dimensional array:
Declares a two-dimensional array with two arrays as elements, with 4 elements of type int in each array
Doublearray: = [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}
If the inner element is the same as the outer one, then the above declaration can be simplified, ignoring the inner type directly
Easyarray: = [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}

2, Slice In many scenarios, arrays do not meet our needs. When we initially define an array, we do not know how large an array is needed, so we need a "dynamic array". In go, this data structure is called slice. Slice is not a real dynamic array, but a Reference type。 Slice always points to an underlying Array,slice declaration can also be like an array, just without the need for length. And declaring an array, just missing the length var fslice []intNext we can declare a slice and initialize the data as follows: slice: = []byte {' A ', ' B ', ' C ', ' d '}slice can be declared again from an array or an already existing slice. slice through array[i:j] to get, where I is the starting position of the array, J is the end position, but does not contain array[j], it's length is j-i。
Declares an array containing 10 elements of type Byte
var ar = [10]byte {' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}
Declares two slice that contain a byte
var a, b []byte
A points to the 3rd element of the array, and ends with the fifth Element,
A = Ar[2:5]    
B is another slice of the array ar
b = Ar[3:5]    
Note the difference between the slice and the declaration: When declaring an array, the length of the array is indicated in square brackets or used ... The length is automatically calculated, and when the slice is declared, there are no characters in the square brackets.
Slice has some simple operations
    • The default starting position for slice is 0,Ar[:n] is equivalent to ar[0:n]
    • The second sequence of slice is the length of the array by default,Ar[n:] equivalent to Ar[n:len (AR)]
    • If you get slice directly from an array, you can ar[:] because the default first sequence is 0, the second is the length of the array, that is ar[:] equivalent to Ar[0:len (AR)]
There are several useful built-in functions for slice:
    • Len gets the length of the slice
    • Cap gets the maximum capacity of the slice
    • Append append one or more elements to the slice
    • The copy function copy copies elements from the src of the source slice to the target DST, and returns the number of copied elements
Note: The append function alters the contents of the array referenced by slice, affecting other slice that refer to the same array. But when the slice is not when the remaining space (that is (cap-len) = = 0), the new array space is dynamically allocated. The returned slice array pointer will point to this space, and the contents of the original array will remain unchanged, while other slice referencing this array are unaffected.
The following example shows more about slice:
Declares an array
var array = [10]byte{' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}
Declaration of two Slice
var aslice, Bslice []byte
Demonstrate some simple operations
Aslice = Array[:3]//equivalent to Aslice = Array[0:3] Aslice contains element: A,b,c
Aslice = array[5:]//equivalent to Aslice = Array[5:10] Aslice contains element: F,g,h,i,j
Aslice = array[:]//equivalent to Aslice = Array[0:10] So aslice contains all the elements
Get Slice from slice
Aslice = Array[3:7]//Aslice contains element: d,e,f,g,len=4,cap=7
Bslice = Aslice[1:3]//Bslice contains aslice[1], aslice[2] that is, contains: e,f
Bslice = Aslice[:3]//Bslice contains aslice[0], aslice[1], aslice[2] that is, contains: d,e,f
Bslice = Aslice[0:5]//slice for slice can be extended within the CAP range, at which time Bslice contains: d,e,f,g,h
Bslice = aslice[:]//Bslice contains all elements of Aslice: D,e,f,g

Slice is a reference type,So when the reference changes the value of the element, all other references change that value, such as Aslice and Bslice above, and if the value of the element in Aslice is modified, the corresponding value of the Bslice will change. Conceptually, slice is like a struct, and this structure contains three elements:
    • - Pointer to the starting position of the slice specified in the array
    • - length , that is, the length of the slice
    • - Maximum length , that is, the length of the slice start position to the last position of the array
3. MapThe format is: Map[keytype]valuetypeMap reading and setting is similar to slice, through key operation, but only slice index can only be ' int ' class Type, and map has many more types, which can be int, which can be a string and all the types that fully define the = = and! = operations.
Declaring a key is a dictionary of literals with a value of int, the declaration of which requires the use of make to initialize VAR numbers map[string] int//another way of declaring a map numbers: = Make (map[string] int) numbers["one"] = 1//Assignment numbers["ten"] = 10//Assignment numbers["three"] = 3fmt. Println ("The third number is:", numbers["three"])//Read data//print out such as: The third number is: 3
This map is like the table we normally see, the left column is key, and the right column is the number of points to note when using the map:
  • -Map is unordered , each time the map will be different, it can not be obtained by index, and must be obtained through key
  • -The length of the map is not fixed , that is, like slice, is also a reference type
  • -The built-in len function also applies to the map, returning the number of keys the map has
  • -map values can be easily modified by numbers["One"]=11 can be easily change the dictionary value of key one to one
The initialization of the map can be initialized by Key:val, and the map has a built-in way to determine if a key exists. Delete the elements of the map via delete:
Initialize a dictionary rating: = map[string]float32 {"C": 5, "Go": 4.5, "Python": 4.5, "C + +": 2}//Map has two return values, second return value, if no key exists, then OK is false If OK is truecsharprating, OK: = rating["C #"]if OK {fmt. Println ("C # is in the map and it rating is", csharprating)} else {fmt. Println ("We have no rating associated with C # in the map")}delete (rating, "C")//Remove key for C element
As mentioned above, map is also a reference type, and if two maps point to one level at a time, then one change and the other changes accordingly:
M: = Make (map[string]string) m["Hello"] = "Bonjour" M1: = mm1["Hello"] = "Salut"//Now m["Hello"] the value is already Salut


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.