Array and slice
1. Array static array [Len]type, array type includes the array length and the element's data type, the data type is exactly the same before the value can be assigned
declaring var array [5]byte//declaration automatically initializes the default to the 0 value corresponding to the respective type
Declaration initialization array: = [5]byte{1,2,3,4,5}//byte array of length 5
Declaration initialization array: = [...] The Byte{1,2,3,4,5}//go compiler infers the length 5 based on the element
2. Slice Dynamic Array
Slice is the abstraction and control of the underlying array. It contains three kinds of metadata that Go needs to be managed for the underlying array, namely:
Pointer to underlying array
Length of elements in slice
Capacity of the slice (maximum value to be increased)
Statement:
A, create a nil Slice;slice==nil
var slice0 []byte
//b, create directly and initialize 0 elements one empty slice
var slice1 = []byte{}
Slice2: = []byte{}
//make creates a storage space with an initial value of make ([]byte,5,10) initialization slice and 10 elements reserved for the initial 5 elements
Slice3: = made ([]byte, 5)
Slice4: = Make ([]byte, 0,]
slice5: = Make ([]byte, 0)
Nil Slice declares the slice, commonly used for function returns slice is used; empty slice declares and initializes the slice;
Function:
Append (Slice []type,elems ... Type) usage, Elems can be a row of type data, or it can be slice, because one of the elements is appended, so if you append one slice to another slice you need to bring "...", This means that the elements in the slice are appended to the other slice in turn. It returns a new slice.
Arr: = [...] Int{1, 2, 3, 4, 5}//static array arr
s1: = []int{1, 2, 3, 4, 5} //dynamic slice
s2: = arr[:]
//execute append
s2 = append (s 2, 1, 2)
s2 = append (s2, s1 ...)
S2 = append (s2, arr[:] ...)
Note: If the capacity of the slice is sufficient, the underlying array will not change, otherwise the memory space will be redistributed. At this point, the element that uses the & value operation may be invalidated.
The CAP () function returns the amount of space allocated by the array slice
The Len () function returns the number of elements currently stored in the array slice
Element subscript starting from 0
Slices can be copied from the array,
Array[startindex:endindex]: Gets the element from the StartIndex position in the array to the EndIndex-1 interval. Its slice length is: endindex-startindex
startindex and Endindex are optional
StartIndex when not set, default to start from scratch, endIndex not set when default intercept to end
Reference:
Http://www.jb51.net/article/56828.htm
Http://www.cnblogs.com/howDo/archive/2013/04/25/GoLang-Array-Slice.html
Go language Programming Xu Xiwei