1
0
Fork 0
pr3-sose2026-fork/go/01-basics/08-slices.go

73 lines
1.9 KiB
Go

package main
import (
"fmt"
"slices"
)
func main() {
// A slice is a dynamically-sized, flexible view into the elements of an array.
// In practice, slices are much more common than arrays.
var s []string
fmt.Println("uninit:", s, s == nil, len(s) == 0)
// To create an empty slice with non-zero length, use the built-in make function.
s = make([]string, 3)
fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
// Set and get a value.
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
fmt.Println("len:", len(s))
// Slices can be resliced. This does not copy the slice data.
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
// Deep copy a slice. This creates a new slice with the same length and copies the
// elements from the original slice to the new slice.
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax slice[low:high].
// This selects a half-open range which includes the first element, but excludes the last one.
l := s[2:5]
fmt.Println("sl1:", l)
// This slices up to (but excluding) index 5.
l = s[:5]
fmt.Println("sl2:", l)
// This slices from index 2 to the end of the slice.
l = s[2:]
fmt.Println("sl3:", l)
// You can declare and initialize a slice in a single line as well.
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
// The builtin "slices" package provides a function Equal to compare two slices for equality.
t2 := []string{"g", "h", "i"}
if slices.Equal(t, t2) {
fmt.Println("t == t2")
}
// Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary.
twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}