This example describes the use of slice in the go language. Share to everyone for your reference. Specifically as follows:
Slice points to the value of the array and also contains the length information.
[]t is a slice with an element type of T.
Copy Code code as follows:
Package Main
Import "FMT"
Func Main () {
P: = []int{2, 3, 5, 7, 11, 13}
Fmt. Println ("p = =", p)
For I: = 0; i < Len (p); i++ {
Fmt. Printf ("p[%d] = =%d\n",
I, P[i])
}
}
Slice can be sliced again to create a new slice value that points to the same array.
An expression
Copy Code code as follows:
Represents a slice element from lo to hi-1, containing both ends. So
Copy Code code as follows:
is empty, and
Copy Code code as follows:
There is an element.
Copy Code code as follows:
Package Main
Import "FMT"
Func Main () {
P: = []int{2, 3, 5, 7, 11, 13}
Fmt. Println ("p = =", p)
Fmt. Println ("p[1:4] = =", P[1:4])
Missing low index implies 0
Fmt. Println ("p[:3] = =", P[:3])
Missing high index implies Len (s)
Fmt. Println ("p[4:] = =", P[4:]
}
Slice is created by function make. This assigns a 0-length array and returns a slice to the array:
Copy Code code as follows:
A: = Make ([]int, 5)//Len (a) =5
Slice has length and capacity. The capacity of the slice is the maximum length that the underlying array can grow.
To specify capacity, you can pass the third parameter to make:
Copy Code code as follows:
B: = make ([]int, 0, 5)
Len (b) =0, Cap (b) =5
Slice can be expanded (up to a capacity limit) by "re-slicing":
Copy Code code as follows:
b = B[:cap (b)]//Len (b) =5, Cap (b) =5
b = b[1:]//len (b) =4, Cap (b) =4
Package Main
Import "FMT"
Func Main () {
A: = Make ([]int, 5)
Printslice ("A", a)
B: = make ([]int, 0, 5)
Printslice ("B", B)
c: = B[:2]
Printslice ("C", c)
D: = C[2:5]
Printslice ("D", D)
}
Func Printslice (S string, x []int) {
Fmt. Printf ("%s len=%d cap=%d%v\n",
S, Len (x), Cap (x), X)
}
The 0 value of slice is nil.
The length and capacity of a nil slice are 0.
Copy Code code as follows:
Package Main
Import "FMT"
Func Main () {
var Z []int
Fmt. Println (z, Len (z), Cap (z))
If z = = Nil {
Fmt. Println ("nil!")
}
}
I hope this article will help you with your go language program.