Slices in Go
Slices in Go are an abstraction over arrays.
The length of a Go array cannot be changed, so such a collection is not suitable in certain scenarios. Go provides a flexible and powerful built-in type, the slice ("dynamic array"); compared with arrays, a slice has no fixed length and can have elements appended to it, which may increase the slice's capacity.
Defining a slice
You can define a slice by declaring an array with an unspecified size:
var identifier []type
A slice does not need to have its length specified.
Or use make() function to create a slice:
var slice1 []type = make([]type, len)
也可以简写为
slice1 := make([]type, len)
You can also specify the capacity, where capacity is an optional parameter.
make([]T, length, capacity)
Here len is the length of the array and also the initial length of the slice.
Slice initialization
s :=[] int {1,2,3 }
Initialize a slice directly; [] indicates a slice type,{1,2,3} the initialization values are 1, 2, 3 in order, whose cap=len=3。
s := arr[:]
initialize a slice s, which is a reference to the array arr.
s := arr[startIndex:endIndex]
Creates a new slice from the elements of arr with indices from startIndex to endIndex-1.
s := arr[startIndex:]
If endIndex is omitted, it means up to and including the last element of arr.
s := arr[:endIndex]
If startIndex is omitted, it means starting from the first element of arr.
s1 := s[startIndex:endIndex]
Initialize slice s1 from slice s.
s :=make([]int,len,cap)
through the built-in function make() initialize a slices,[]int identifies it as a slice whose element type is int.
The len() and cap() functions
Slices are indexable, and their length can be obtained with the len() method.
Slices provide a cap() method to compute capacity, which measures the maximum length a slice can reach.
The following is a concrete example:
Example
package
main
import
"fmt"
func
main
()
{
var
numbers
=
make
([]
int
,
3
,
5
)
printSlice
(
numbers
)
}
func
printSlice
(
x
[]
int
){
fmt
.
Printf
(
"len=%d cap=%d slice=%v\n"
,
len
(
x
),
cap
(
x
),
x
)
}
The output of running the above example is:
len=3 cap=5 slice=[0 0 0]
Empty (nil) slice
A slice defaults to nil before initialization, with a length of 0; example as follows:
Example
package
main
import
"fmt"
func
main
()
{
var
numbers
[]
int
printSlice
(
numbers
)
if
(
numbers
==
nil
){
fmt
.
Printf
(
"slice is empty"
)
}
}
func
printSlice
(
x
[]
int
){
fmt
.
Printf
(
"len=%d cap=%d slice=%v\n"
,
len
(
x
),
cap
(
x
),
x
)
}
The output of running the above example is:
len=0 cap=0 slice=[]
切片是空的
Slicing
You can slice by setting a lower and upper bound [lower-bound:upper-bound]; the example is as follows:
Example
package
main
import
"fmt"
func
main
()
{
/* create a slice */
numbers
:=
[]
int
{
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
}
printSlice
(
numbers
)
/* print the original slice */
fmt
.
Println
(
"numbers =="
,
numbers
)
/* print the sub-slice from index 1 (inclusive) to index 4 (exclusive)*/
fmt
.
Println
(
"numbers[1:4] =="
,
numbers
[
1
:
4
])
/* default lower bound is 0*/
fmt
.
Println
(
"numbers[:3] =="
,
numbers
[:
3
])
/* default upper bound is len(s)*/
fmt
.
Println
(
"numbers[4:] =="
,
numbers
[
4
:])
numbers1
:=
make
([]
int
,
0
,
5
)
printSlice
(
numbers1
)
/* print the sub-slice from index 0 (inclusive) to index 2 (exclusive) */
number2
:=
numbers
[:
2
]
printSlice
(
number2
)
/* print the sub-slice from index 2 (inclusive) to index 5 (exclusive) */
number3
:=
numbers
[
2
:
5
]
printSlice
(
number3
)
}
func
printSlice
(
x
[]
int
){
fmt
.
Printf
(
"len=%d cap=%d slice=%v\n"
,
len
(
x
),
cap
(
x
),
x
)
}
The output of the code above is:
len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
len=0 cap=5 slice=[]
len=2 cap=9 slice=[0 1]
len=3 cap=7 slice=[2 3 4]
The append() and copy() functions
If you want to increase a slice's capacity, you must create a new, larger slice and copy all the original slice's contents into it.
The following code describes the copy method for copying a slice and the append method for adding new elements to a slice.
Example
package
main
import
"fmt"
func
main
()
{
var
numbers
[]
int
printSlice
(
numbers
)
/* allows appending to an empty slice */
numbers
=
append
(
numbers
,
0
)
printSlice
(
numbers
)
/* add one element to the slice */
numbers
=
append
(
numbers
,
1
)
printSlice
(
numbers
)
/* add multiple elements at once */
numbers
=
append
(
numbers
,
2
,
3
,
4
)
printSlice
(
numbers
)
/* create slice numbers1 with twice the capacity of the previous slice*/
numbers1
:=
make
([]
int
,
len
(
numbers
),
(
cap
(
numbers
))
2
)
/* copy the contents of numbers into numbers1 */
copy
(
numbers1
,
numbers
)
printSlice
(
numbers1
)
}
func
printSlice
(
x
[]
int
){
fmt
.
Printf
(
"len=%d cap=%d slice=%v\n"
,
len
(
x
),
cap
(
x
),
x
)
}
The output of the above code is:
len=0 cap=0 slice=[]
len=1 cap=1 slice=[0]
len=2 cap=2 slice=[0 1]
len=5 cap=6 slice=[0 1 2 3 4]
len=5 cap=12 slice=[0 1 2 3 4]