7. Array:
is almost the most commonly used data type ...
An array is a collection of a series 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.
General method of Array declaration:
[32]byte //array of length 32, each element is a byte [2*n] struct {x, y Int32}//Complex type array [1000]*float32//pointer array [3][5]int//two-D array [2][2][2] Float64 //equivalent to [2] ([2] ([2]float64))
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)
A, element access
You can use array subscripts to access the elements in an array. 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])}
You can also use range to traverse
For I, V: = range array { FMT. Println ("Array element[", I, "]=", V)}
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.
B, Value type
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.
Example:
Package Mainimport "FMT" func Modify (array [10]int) {
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 attempt to modify this array content in the function body FMT. PRINTLN ("in Main (), array values:", Array)}
The execution result of the program is:
In modify (), array values: [10 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? You can use the array slicing feature to achieve this goal.
8. Array slicing:
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 transferred at will without causing the managed elements to be duplicated.
A, creating an array slice
There are two main ways to create an array slice-based on arrays and direct creation-let's take a brief look at both of these methods.
? Based on Array
Array slices can be created based on an existing array. Array slices can be created using only a subset of the elements of an array or an entire array, or even an array slice larger than the array on which it is based.
Code Listing 2-1 (SLICE.GO) demonstrates how to create an array slice based on the first 5 elements of an array.
Package Mainimport "FMT" Func Main () { //First define an array var myArray [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}//Base Create an array of arrays in the array 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 ()}
The result of the operation is:
Elements of MyArray:
1 2 3 4 5 6 7 8 9 10
Elements of Myslice:
1 2 3) 4 5
Go language support uses myarray[first:last] to generate an array slice based on an array , and this usage is 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:]
? Create directly (make () )
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}
In fact, there will be an anonymous array created, but we don't need to worry about it.
B, Element traversal
All methods that manipulate array elements apply to array slices, such as array slices, which can also read and write elements by subscript, get the number of elements using the Len () function, and support the use of the range keyword to quickly traverse all elements.
The traditional method of element traversal is as follows:
For I: = 0; I <len (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 {
Comparing the two methods above, we can easily see that the code using range is more straightforward to understand.
C, dynamic addition and subtraction of elements
The ability to dynamically add or subtract elements is a more powerful feature of array slices than arrays. Compared to arrays, array slices have a more storage capability (capacity) concept, that is, the number of elements and the allocated space can be two different values. Reasonable setting of the value of the storage capacity can greatly reduce the frequency of the internal redistribution of memory and the number of memory blocks in the array tiles, thus significantly improving program performance.
If you know for sure that the currently created array slice may need to store as many as 50 elements, then if you set a storage capacity of less than 50, such as 20, then at least one of these actions will occur at the bottom of the element at more than 20 o'clock- -reallocate a "big enough" memory, And it is necessary to copy the content from the original memory block to the newly allocated memory block, which has a significant overhead. the word "big enough" is quoted because the system doesn't know how big it is, so it's just a simple guess. For example, expanding the original memory space by twice times, but twice times is not necessarily enough, so the memory redistribution and content replication process mentioned earlier is likely to occur many times, thus significantly reducing the overall performance of the system. But if you know the maximum is 50 and set the storage capacity at the beginning of 50, then there will not be such a very CPU-intensive action, so as to achieve the effect of space exchange time.
Array slices support the go language built-in cap () function and the Len () function, and code listing 2-2 (SLICE2.GO) simply demonstrates the use of these two built-in functions. As you can see, thecap () function returns the amount of space allocated by the array slice, and the Len () function returns 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): 5
Cap (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, that is, an ellipsis, if there is no such ellipsis, there will be a compilation error , because by the semantics of append (), all parameters from the second parameter are the elements to be attached. Because the element type in Myslice is int, it is not feasible to pass MYSLICE2 directly. the ellipsis is equivalent to breaking all the elements contained in the MySlice2 and passing in.
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.
D. Creating array slices based on array slices
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
E, Content Replication
Array slices support another built-in function copy () of the Go language, which is used to copy content from one array slice to another array slice. If you add two array slices that are not the same size, they will be copied by the number of elements in the smaller array. 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, slice 2)//Copy only 3 elements of Slice2 to the first 3 locations of Slice1
Not to be continued ...
"Go" Go language learning note three