Concept: array-based, array slicing adds a series of management functions that dynamically expand the storage space at any time and do not cause the managed elements to be duplicated.
To create an array slice:
Method one, array-based:
Package Mainimport "FMT" Func Main () {//define an arrayvar myArray [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}//create A slice based on arrayvar 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 ()}
Operation Result:
Elements of MyArray:
1 2 3 4 5 6 7 8 9 10
Elements of Myslice:
1 2 3) 4 5
Method Two, create directly:
The built-in function make () provided by Golang can be used to flexibly create array slices.
Create an array slice with an initial element number of 5, with an element initial value of 0:
Myslice: = 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:
Myslice: = Make ([]int, 5, 10)
Create and initialize an array slice that contains 5 elements directly:
Myslice: = []int{1, 2, 3, 4, 5}
Traverse:
Traditional traversal:
For i:=0; I<len (Myslice); i++ {
Fmt. Println ("myslice[", I, "] =", myslice[i])
}
Range Traversal:
For I, V: = Range Myslice {
Fmt. Println ("myslice[", I, "] =", V)
}
Storage capacity (capacity):
Concept: The number of elements and the allocated space can be two different values.
Cap (): Returns the amount of space allocated for the array slice
Len (): 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))}
Output Result:
Len (myslice): 5
Cap (Myslice): 10
Append ():
Continuing with the new element, the following code adds three elements from the end to Myslice, creating a new array slice.
Myslice = Append (Myslice, 1, 2, 3)
The following code appends an array slice directly to the end of another array slice.
MySlice2: = []int{8, 9, 10}
Myslice = Append (Myslice, MySlice2 ...)
To create an array slice based on an array slice:
Oldslice: = []int{1, 2, 3, 4, 5}
Newslice: = Oldslice[:3]
Copy ():
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
Copy (Slice1, SLICE2)//Copy Slice2 3 elements to the first three locations of Slice1
Array slices in the Golang