Go language Learning (ii): array, slices, and map

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

Objective

Recently more than a month busy with the paper, all aspects of the synthesis of reasons, said that many are tears, waiting for the results. On the Go language learning, the content of this article has long been studied, before the time did not know where to go, but also no mind, now transcribe it up.

Arrays Array


Definition form: [ N], n indicates the array length, The label type.
E.g:[32]byte      //Length 32 array, each element is 1 Byte[16]*float64  //pointer array [3][5]int     //two-D array
In the go language, the length of the array cannot be changed after it is defined. Get array element number method: Arrlength: = Len (array)
Element access is consistent with C. It is important to note that the array in the go language belongs to value type, and cannot be used for pointer passing like C. Other words if the array is a function-in parameter, when the function is called, the function makes a copy copy of the array, and the function modifies the contents of the copy .。
E.gpackage mainimport "FMT" func Modify (array [5]int) {array[0] = 10fmt. Println ("in Modify (), array values:", array[0])}func main () {array: = [5]int{1, 2, 3, 4, 5}modify (array) fmt. PRINTLN ("in Main (), array values:", Array[0])}

Array slicing slices


Array features: Length can no longer be modified after definition; value type;
If you need to use an array as a function parameter for pointer passing, in which case the go language uses array tiles to satisfy that requirement. Therefore, array slices belong to the Reference type
Array slices have their own data structure, which can be abstracted into the following 3 variables:
    1. A pointer to the native array, which still creates an array at the bottom, with a pointer to the array in the array slice structure;
    2. The number of elements in the array slice;
    3. The allocated storage space for the array slice;

Array Tile creation

    • Based on Array
E.gvar MyArray [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}var myslice []int = Myarray[:5]  //GO language support with Myarray[fi Rst:last] Format Select array elements
    • Directly create
Use built-in function make () to create flexibly, or directly initialize the creation.
E.gmyslice1: = Make ([]int, 5)        //Create an array slice with a number of 5 elements, default initialized to 0myslice2: = Make ([]int, 5, Ten)    ///Ibid, But the total reserved is 10 elements of storage space mySlice3: = []int{1, 2, 3, 4, 5}  //Create and initialize an array slice with 5 elements directly
    • Based on slices
E.goldslice: = []int{1, 2, 3, 4, 5}newslice: = Oldslice[:3]  //build new array slices based on oldslice first 3 elements
Similar to array slicing based on array creation, the difference between creating a new array based on an old slice can exceed the number of elements that are contained, and the element part is initialized to 0, but there is one limitation that the old tile storage space must be exceeded.

Dynamic increment and decrement elements


Array slicing has a concept of storage capability, i.e. The number of elements and allocation space can be two different values。 In order to significantly reduce the internal redistribution of memory and the frequency of the memory block in the array tiles, the provider performance requires us to set the value of the storage capacity reasonably.
The array slice supports the go language's built-in Cap () and Len () functions, and the CAP () returns the array tile allocation space value, and Len () returns the number of elements stored in the slice.

Use the Append () built-in function if you need to continue adding new elements to the elements that Myslice already contain.
E.gmyslice = Append (Myslice, 1, 2, 3)      //Add plain element myslice = append (Myslice, MySlice1 ...)  Add a slice and note that the following "..." must not be omitted
Array slices automatically handle the problem of insufficient storage space. If the appended content is longer than the currently allocated storage space, the array slice is automatically allocated a chunk of memory that is large enough. This is also the reason why you should set the storage space value reasonably.

Another slice supports the go language's built-in function copy (), which is used to copy content from one slice to another. If you add two slices that are not the same size, copy the number of elements in the smaller slice.
e.g Slice1: = []int{1, 2, 3, 4, 5}slice2: = []int{5, 4, 3}copy (Slice2, Slice1)  //copy Slice1 first three elements to Slice2 in copy (Slice1 , Slice2)  //Copy the 3 elements of the Slice2 to the first 3 locations of the SLICE2

Key-value pairs map


Map is an unordered collection of key-value pairs.
    • Variable declaration
E.gvar MyMap Map[string] PersonInfo
Where Mymap is the name of the declared map variable, string is the type, and Personinfo is the type of value it holds.

The built-in function make () is still used to create a map.
E.gmymap = Make (map[string] PersonInfo, 100)
Or the code to create and initialize the map directly is as follows:
E.gmymap = map[string] PersonInfo {"1234": personinfo{"1", "Jack", "101, ..."}
    • Add to:
e.gmymap["456"] = personinfo{"2", "Bob", "102, ..."
    • Delete:
Use the built-in function delete () to delete elements inside the container.
    • Find:
Use the following code to implement a lookup:
E.gvalue, OK: = mymap["1234"]if OK {//found, processing ...}
These lines of code indicate that you just need to look at the second return value OK, very simple:
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.