slices
The slice (slice) itself is not a dynamic array or an array pointer. It internally sets the action to the specified array by referencing the underlying array and setting the correlation property.
There are three properties: the underlying array pointer, length, capacity.
Length refers to the length of the current slice, which is the length at which the underlying array has been stored.
Capacity is the maximum length that a slice can use, not necessarily the length of the underlying array. Defining and initializing
Slices can be obtained from existing arrays, or they can be created directly.
Because a slice is a reference type, the underlying array is not assigned when created directly, so memory allocation is done using the Make function or the display initialization statement.
Package main
Import (
"FMT"
)
func main () {
arr: = [...] Int{1, 2, 3} //array
SLC: = arr[:] //slice with arr array created for the underlying array
slc_a: = []int{1, 2, 3} //slice (display initialization)
SLC _b: = Make ([]int, 3, 4) // slice (make function)
FMT. Printf ("%t\n", SLC)
FMT. Printf ("%t\n", slc_a)
FMT. Printf ("%t\n", Slc_b)
}
Make function Signature: Func make (type, size Integertype) Type
The slice's capacity is greater than or equal to the length.
Package main
Import (
"FMT"
)
func main () {
SLC: = Make ([]int, 3, 4) //Length 3 Volume 4
//SLC: = Make ([]int, 3) Length 3 Volume 3
fmt. Printf ("Slice len =%d, Cap =%d\n", Len (SLC), Cap (SLC))
}
Slice is a reference type, and initialization is nil.
Package main
Import (
"FMT"
)
func main () {
var SLC []int/ /define only
B: = []int{} / /define simultaneous initialization of
FMT. PRINTLN (SLC = = nil)
FMT. Println (b = = nil)
}