starting go by example
This commit is contained in:
60
5-go-by-example/9-slices.go
Normal file
60
5-go-by-example/9-slices.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Slices are a key data type in Go, giving a more powerful interface to sequences than arrays
|
||||
func main() {
|
||||
|
||||
// slices are typed only by the elements they contain (not the number of elements)
|
||||
// Here make a slice of strings of length 3 (initially zero-valued)
|
||||
s := make([]string, 3)
|
||||
fmt.Println("emp:", s)
|
||||
|
||||
// set and get like with arrays
|
||||
s[0] = "a"
|
||||
s[1] = "b"
|
||||
s[2] = "c"
|
||||
fmt.Println("set:", s)
|
||||
fmt.Println("get:", s[2])
|
||||
|
||||
// len returns the length of the slice as expected
|
||||
fmt.Println("len:", len(s))
|
||||
|
||||
// returns a slice containing one or more new values
|
||||
s = append(s, "d")
|
||||
s = append(s, "e", "f")
|
||||
fmt.Println("apd:", s)
|
||||
|
||||
// create an empty slice c of the same length as s and copy into c from s
|
||||
c := make([]string, len(s))
|
||||
copy(c, s)
|
||||
fmt.Println("cpy:", c)
|
||||
|
||||
// Slices support operators with the syntax slice[low:high]
|
||||
l := s[2:5]
|
||||
fmt.Println("sl1:", l)
|
||||
|
||||
// slices up to (but excluding) s[5]
|
||||
l = s[:5]
|
||||
fmt.Println("sl2:", l)
|
||||
|
||||
// slices up from (and including) s[2]
|
||||
l = s[2:]
|
||||
fmt.Println("sl3:", l)
|
||||
|
||||
// declare and initialize a variable for slice in a single line
|
||||
t := []string{"g", "h", "i"}
|
||||
fmt.Println("dcl:", t)
|
||||
|
||||
// Slices can be composed into multi-dimensional data structures
|
||||
// The length of the inner slices can vary, unlike with multi-dimensional arrays
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user