Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
86 lines (73 loc) · 2.4 KB
/
Copy pathmain.go
File metadata and controls
86 lines (73 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Slices are an important data type in So, giving
// a more powerful interface to sequences than arrays.
package main
import "solod.dev/so/fmt"
func main() {
// Unlike arrays, slices are typed only by the elements
// they contain (not the number of elements).
// An uninitialized slice equals to nil and has length 0.
var s []string
printSlice("uninit:", s)
println("len:", len(s), "cap:", cap(s))
// To create a slice with non-zero length, use the `make` builtin.
// Here we make a slice of `string`s of length `3` (initially zero-valued).
// By default a new slice's capacity is equal to its length;
// if we know the slice is going to grow, we must pass a capacity
// as an additional parameter to `make` (`6` in this case).
s = make([]string, 3, 6)
printSlice("emp:", s)
println("len:", len(s), "cap:", cap(s))
// We can set and get just like with arrays.
s[0] = "a"
s[1] = "b"
s[2] = "c"
printSlice("set:", s)
println("get:", s[2])
// `len` returns the length of the slice as expected.
println("len:", len(s))
// The `append` builtin returns a slice containing one or
// more new values. Note that we need to accept a return
// value from `append` as we may get a new slice value.
s = append(s, "d")
s = append(s, "e", "f")
printSlice("append:", s)
// By default, slices in So are stack-allocated, and
// cannot grow beyond their initial capacity.
// To allocate a slice on the heap and grow it beyond
// its initial capacity, use the `so/mem` package.
// Slices can also be `copy`'d. Here we 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)
printSlice("copy:", c)
// Slices support a "slice" operator with the syntax
// `slice[low:high]`. For example, this gets a slice
// of the elements `s[2]`, `s[3]`, and `s[4]`.
l := s[2:5]
printSlice("s[2:5] =", l)
// This slices up to (but excluding) `s[5]`.
l = s[:5]
printSlice("s[:5] =", l)
// And this slices up from (and including) `s[2]`.
l = s[2:]
printSlice("s[2:] =", l)
// We can declare and initialize a variable for slice
// in a single line as well.
t := []string{"g", "h", "i"}
printSlice("dcl:", t)
}
func printSlice(msg string, s []string) {
if len(s) == 0 {
fmt.Printf("%s []\n", msg)
return
}
fmt.Printf("%s", msg)
fmt.Printf(" [")
for i, v := range s {
fmt.Printf("%s", v)
if i < len(s)-1 {
fmt.Printf(" ")
}
}
fmt.Printf("]\n")
}