Getting Started with Go language basics-arrays, slices, maps

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

Array

arrays are one of the most commonly used data structures in go language programming. As the name implies, an array refers to a collection of data of the same type. Each data contained in an array is called an array element, and the number of elements contained in an array is called the length of the array.
Here are some general methods of array declaration:
[+] Byte//array of length 32, each element is a byte [2*n] struct {x, y Int32}//Complex type array [1000]*float64//pointer array [3][5] Int//two d array [2][2][2] Flo At64//equivalent to [2] ([2] ([2]float64))
As can be seen from the above types, arrays can be multidimensional, for example [3][5]int] expresses a two-dimensional integer array of 3 rows and 5 columns, which can hold 15 integral elements in total.
In the go language, the length of an array cannot be changed after it is defined, and the length can be a constant or a constant expression when declared (a constant expression is an expression that evaluates the result at compile time). The length of the array is a built-in constant for the array type, which can be obtained using the go language's built-in function Len (). Here is a notation for getting the number of ARR elements in an array: arrlength: = Len (arr)
1. Element access
You can use array subscripts to access the elements in an array. As with the C language, array subscripts start at 0, and Len (array)-1 indicates the subscript of the last element. The following example iterates through an array of integers and prints the contents of the elements individually:
For I: = 0; I < Len (array); i++ {fmt. Println ("Element", I, "of array is", array[i])}for I: = 0; I < Len (array); i++ {fmt. Println ("Element", I, "of array is", Array[i])}
The Go language also provides a keyword range that allows you to easily traverse the elements in a container. Of course, the array is also a range of support. The above traversal process can be simplified to the following notation:
For I, V: = range array {fmt. Println ("Array element[", I, "]=", V)}
As you can see in the above example, range has two return values, the first return value is an array subscript for the element, and the second return value is the value of the element.
2. Value types
It is important to note that in the go language an array is a value type. All value-type variables produce a copy action when they are assigned and passed as arguments. If you use an array as the parameter type for a function, the parameter will occur when the function is called for data replication. Therefore, the contents of the incoming array cannot be modified in the body of the function, because only one copy of the incoming array is manipulated inside the function.
Here is an example to illustrate this feature:
Package Mainimport "FMT" func Modify (array [x] int) {ARRAY[0] = 10//Try to modify the first element of the array fmt. Println ("in Modify (), array values:", array)}func main () {array: = [5] int{1,2,3,4,5}//define and initialize an array modify (array)//pass to a function and try to modify the contents of this array in the body of the FMT. PRINTLN ("in Main (), array values:", Array)}
The execution result of the program is:
In modify (), array values: [2 3 4 5]in Main (), array values: [1 2 3 4 5]
As you can see from the execution results, the array in which the function modify () operates is two different instances from the array passed in main (). So how can you manipulate external data structures within a function? We will detail how to use the array slicing function to achieve this goal in section 2.3.6.

Array slices

In the previous section we have mentioned the characteristics of the arrays: the length of the array cannot be modified after the definition, the array is a value type, and each pass produces a copy. Obviously this data structure does not fully meet the real needs of developers.
Without disappointment, the Go language provides array slicing (slice), a very cool feature to compensate for the lack of arrays. At first glance, an array slice is like a pointer to an array, and in fact it has its own data structure, not just a pointer. The data structure of an array slice can be abstracted into the following 3 variables:
A pointer to the native array;
The number of elements in the array slice;
The array slice has allocated storage space.
From the perspective of the underlying implementation, array slices actually still use arrays to manage elements, so the relationship between them makes it easy for C + + programmers to associate std::vector and arrays in STL. Array-based, array slicing adds a series of management functions that can dynamically expand the storage space at any time, and can be arbitrarily passed without causing the managed elements to be duplicated very much.
1. Creating an Array slice
There are two main ways to create an array slice-based on arrays and direct creation, and here's a brief look at the two types of
Method.
Based on Array
Array slices can be created based on an existing array. Array slices can use only a subset of the elements of an array or the entire
Array to create, you can even create an array slice larger than the array on which it is based. Code Listing 2-1 demonstrates how the base
Creates an array slice of the first 5 elements of an array.
Package Mainimport "FMT" Func Main () {//First define an array var myArray [ten] int = [2] int{1,, 3, 4, 5, 6, 7, 8, 9, 10}//array-based creation of a Array of tiles var myslice [] int = Myarray[:5] FMT. Println ("Elements of MyArray:") for _, V: = Range MyArray {fmt. Print (V, "")} FMT. Println ("\nelements of Myslice:") for _, V: = Range Myslice {fmt. Print (V, "")} FMT. Println ()} Run Result: Elements of Myarray:1 2 3 4 5 6 7 8 9 10Elements of Myslice:1 2 3 4 5
It has been noted that the go language supports using myarray[first:last] to generate an array based
The number of slices, and this usage is also very flexible, such as the following are legal.
To create an array slice based on all elements of myarray:
Myslice = myarray[:]
Create an array slice based on the first 5 elements of MyArray:
Myslice = Myarray[:5]
Creates an array slice based on all elements starting from the 5th element:
Myslice = myarray[5:]
Directly create
It is not always necessary to prepare an array in advance to create an array slice. The Go language provides built-in function make () that can be used to
Flexibility to create array slices. The following example demonstrates the various ways to create an array slice directly.
Create an array slice with an initial element number of 5, with an element initial value of 0:
MySlice1: = make ([] int, 5)
Create an array slice with an initial element number of 5, an element with an initial value of 0, and a storage space of 10 elements:
MySlice2: = make ([] int, 5, 10)
Create and initialize an array slice that contains 5 elements directly:
MySlice3: = [] Int{1, 2, 3, 4, 5}
Of course, there's actually an anonymous array created, but we don't need to worry about it.
2. Element traversal
All methods that manipulate array elements apply to array slices, such as array slices, which can also be read and written by the subscript, with Len ()
The function gets the number of elements and supports using the range keyword to quickly traverse all elements.
The traditional method of element traversal is as follows:
For I: = 0; I <len (myslice); i++ {fmt. Println ("myslice[", I, "] =", Myslice[i])}
Use the range keyword to make the Traverse code look neater. The range expression has two return values, the first of which is the index,
The second one is the value of the element:
For I, V: = Range Myslice {fmt. Println ("myslice[", I, "] =", V)}
Comparing the two methods above, we can easily see that the code using range is more straightforward to understand.
3. Dynamic addition and subtraction of elements
The ability to dynamically add or subtract elements is a more powerful feature of array slices than arrays. Array slices have a more storage capacity than arrays
The concept of force (capacity), that is, the number of elements and the space allocated can be two different values. The ability to set storage appropriately
Value, which greatly improves program performance by significantly reducing the frequency with which memory is redistributed and the memory blocks are moved inside the array tiles.
If you know for sure that the currently created array slice may require a maximum of 50 elements to be stored, then if you set the
The storage capacity is less than 50, such as 20, then at least one of these actions will occur at the bottom of the element in excess of 20 o'clock--re-
With a "big enough" memory, and you need to copy the content from the original memory block to the newly allocated memory block, which results in a comparison
Obvious overhead. The reason for the word "big enough" is that the system doesn't know how big it is, so it's just a
A simple guess. For example, the original memory space is enlarged by twice times, but twice times is not necessarily enough, so the previously mentioned memory re-
The process of allocation and content replication is likely to occur more than once, thereby significantly reducing the overall performance of the system. But if you know the biggest is
50 and the storage capacity is set at the beginning of 50, then there will not be such a very CPU-intensive action, so as to achieve the effect of space-changing time.
Array slices support the go language built-in cap () function and the Len () function, and listing 2-2 simply demonstrates the two built-in
The use of functions. As you can see, the CAP () function returns the amount of space allocated by the array slice, and the Len () function returns the
The number of elements currently stored in the array slice.
Package Mainimport "FMT" Func Main () {myslice: = make ([] int, 5, ten) fmt. Println ("Len (myslice):", Len (Myslice)) fmt. Println ("Cap (Myslice):", Cap (Myslice))}
The output of this program is:
Len (myslice): 5cap (myslice): 10
You can use the Append () function if you need to continue adding new elements after the 5 elements that Myslice already contain in the previous example.
The following code can add 3 elements from the end to Myslice to generate a new array slice:
Myslice = Append (Myslice, 1, 2, 3)
The second parameter of the function append () is actually an indeterminate parameter, and we can add several elements to our own needs.
Even append an array slice directly to the end of another array slice:
MySlice2: = [] int{8, 9, 10}//add another array slice after myslice Myslice = append (Myslice, MySlice2 ...)
Note that we add three points after the second parameter MySlice2, which is an ellipsis, without which the province
Number, there will be a compile error, because the semantics of append (), all parameters from the second parameter are to be appended
Elements. Because the element type in Myslice is int, it is not feasible to pass MYSLICE2 directly. Plus the ellipsis phase,
When all the elements contained in the MySlice2 are scattered, they are passed in.
The above call is equivalent to:
Myslice = Append (Myslice, 8, 9, 10)
Array slices automatically handle the problem of insufficient storage space. If the appended content is longer than the currently allocated storage space
(That is, the information returned by the CAP () call), the array slice is automatically allocated a chunk of memory that is large enough.
4. Creating an array slice based on an array slice
Similar to array slices can be created from an array, and array slices can also be created based on another array slice. The following
Example creates a new array slice based on an existing array slice:
Oldslice: = [] Int{1, 2, 3, 4, 5}newslice: = Oldslice[:3]//build new array slices based on oldslice first 3 elements
Interestingly, the range of OLDSLICEF elements selected can even exceed the number of elements contained, such as Newslice
Can be created based on the first 6 elements of Oldslice, although Oldslice contains only 5 elements. As long as the range of this selection is not super
Oldslice storage capacity (that is, the value returned by the CAP ()), the creation process is legal. Newslice out of
The part of the Oldslice element is filled with 0.
5. Content Replication
Array slices support another built-in function copy () for the Go language, which is used to copy content from one array slice to another
Array slices. If you add two array slices that are not the same size, the number of elements in the smaller array will be
Copy. The following example shows the behavior of the copy () function:
Slice1: = [] Int{1, 2, 3, 4, 5}slice2: = [] int{5, 4, 3}copy (Slice2, Slice1)//Only the first 3 elements of Slice1 are copied to Slice2 in copy (Slice1, Slic E2)//Copy only 3 elements of Slice2 to the first 3 locations of Slice1

Map

In C++/java, maps are generally provided as libraries, such as STL's STD::MAP<> in C + +;
Dictionary<>, in Java, is hashmap<> in these languages, if you want to use a map, refer to the corresponding
Library. In go, using map does not need to introduce any libraries, and it is more convenient to use them.
Map is an unordered collection of key-value pairs. For example, to identify a person's information with a social security number as a unique key, the
Map can be defined as the way it looks in listing 2-3.
Package Mainimport "FMT"//PersonInfo is a type containing personal details types PersonInfo struct {ID string Name string Address string}func Main () {var persondb map[string] PersonInfo persondb = make (map[string] PersonInfo)//insert several data into this map persondb["12345"] = Pe rsoninfo{"12345", "Tom", "The 203,..."} persondb["1"] = personinfo{"1", "Jack", "the" "101,..."}//from this map to find the key "1234" information person, OK: = persondb["1234"]<pre name= "code" class= "CPP" >//OK is a return bool type, returning TRUE indicates that the corresponding data was found if OK {fmt. Println (' Found person ', person. Name, "with ID 1234.") } else {fmt. Println ("Didn't not find the person with ID 1234.")}}
This simple example above basically covers the main usage of the map, and the key points below are described in detail. 1. The Declaration of a variable declaration map basically has no extraneous elements, such as:
var myMap map[string] Personinfomymap = Make (map[string] PersonInfo)
Where Mymap is the name of the declared map variable, string is the type of the key, and Personinfo is the value type in which it is stored. 2. Create we can use the go language built-in function make () to create a new map. The following example creates a map with a key type of string and a value of type personinfo:
MyMap = Make (map[string] PersonInfo)
You can also choose whether to specify the initial storage capacity of the map at creation time, and the following example creates an initial storage capability
Map for 100:
MyMap = Make (map[string] PersonInfo, 100)
The code to create and initialize the map is as follows:
MyMap = map[string] personinfo{"1234": personinfo{"1", "Jack", "Hostel 101,..."},}
3. Assigning values to elements
The assignment process is simple and straightforward, which is to correspond the keys and values in the following way:
mymap["1234"] = personinfo{"1", "Jack", "101,..."}
4. Element deletion
The go language provides a built-in function delete () to delete elements within a container. Let's briefly explain
How to delete an element in a map with the Delete () function:
Delete (MyMap, "1234")
5. Element Lookup
In the Go language, map lookup functions are designed to be more sophisticated. In other languages, it is not easy to determine whether a value can be obtained. The general practice of judging whether a value can be obtained from a map is:
(1) Declaring and initializing a variable to be null;
(2) Attempt to obtain the value of the corresponding key from the map into the variable;
(3) Determine if the variable is still empty, or null if the variable is not included in the map.
This usage is a bit more, and judging whether the variable is empty this statement does not really mean (whether to successfully fetch the corresponding
Value), which can affect the readability and maintainability of the code. Some libraries are even designed to throw exceptions because a key doesn't exist.
Let the developer use to fear, have to layer nested Try-catch statement, this is not humanized design. In Go
Language, to find a specific key from the map, you can use the following code to implement
Value, OK: = mymap["1234"]if OK {//found//processing found value}
To determine if a particular key was found successfully, do not need to check to see if the value is nil, just look at the second return value OK,
This makes the meaning of the table much clearer. Mates: = operator, so that your code does not have redundant ingredients, it looks very clear and understandable.
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.