There are many ways to initialize slices, which can be initialized directly, or used array initialization, etc.
How to cut slices
package main import "fmt" // Slicefunc test1() { var s1 = []int{1, 2, 3, 4, 5, 6} s2 := s1[0:3] // [) ("s2: %v\n", s2) s3 := s1[3:] ("s3: %v\n", s3) s4 := s1[2:5] ("s4: %v\n", s4) s5 := s1[:] ("s5: %v\n", s5) } func main() { test1() }
Running results
[Running] go run "/Users/guoliang/SynologyDrive/Software Development/go/golang Getting Started to Project Practical/goproject//pro01/"
s2: [1 2 3]
s3: [4 5 6]
s4: [3 4 5]
s5: [1 2 3 4 5 6]
Direct initialization
package main import "fmt" func main() { s := []int{1, 2, 3} ("s: %v\n", s) }
Running results
[Running] go run "/Users/guoliang/SynologyDrive/Software Development/go/golang Getting Started to Project Practical/goproject//pro01/"
s: [1 2 3]
Initialization with array
package main import "fmt" func main() { arr := [...]int{1, 2, 3} s1 := arr[:] ("s1: %v\n", s1) }
Running results
[Running] go run "/Users/guoliang/SynologyDrive/Software Development/go/golang Getting Started to Project Practical/goproject//pro01/"
s1: [1 2 3]
Initialization using partial elements of an array (slice expression)
The bottom layer of a slice is an array, so we can get slices based on the array through slice expressions. The low and high in the slice expression represent an index range (including left and not right), and the resulting slice length = high-low, and the capacity is equal to the capacity of the underlying array of the obtained slice.
package main import "fmt" func main() { arr := [...]int{1, 2, 3, 4, 5, 6} s1 := arr[2:5] ("s1: %v\n", s1) s2 := arr[2:] ("s2: %v\n", s2) s3 := arr[:3] ("s3: %v\n", s3) }
Running results
[Running] go run "/Users/guoliang/SynologyDrive/Software Development/go/golang Getting Started to Project Practical/goproject//pro01/"
s1: [3 4 5]
s2: [3 4 5 6]
s3: [1 2 3]
Empty (nil) slices
A slice defaults to nil before it is not initialized, with a length of 0 and a capacity of 0.
package main import "fmt" func main() { var s1 []int (s1 == nil) ("len: %d, cap: %d\n", len(s1), cap(s1)) }
Running results
[Running] go run "/Users/guoliang/SynologyDrive/Software Development/go/golang Getting Started to Project Practical/goproject//pro01/"
true
len: 0, cap: 0
This is the end of this article about the use examples of golang slice initialization. For more related golang slice initialization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!