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
|
package main
func main() {
l := 5
foo := []int{1, 2, 4, 5}
bar := make([]int, l-2, l)
println("foo is nil?", foo == nil, nil == foo)
printslice("foo", foo)
printslice("bar", bar)
printslice("foo[1:2]", foo[1:2])
println("sum foo:", sum(foo))
// copy
println("copy foo -> bar:", copy(bar, foo))
printslice("bar", bar)
// append
var grow []int
println("slice is nil?", grow == nil, nil == grow)
printslice("grow", grow)
grow = append(grow, 42)
printslice("grow", grow)
grow = append(grow, -1, -2)
printslice("grow", grow)
grow = append(grow, foo...)
printslice("grow", grow)
grow = append(grow)
printslice("grow", grow)
grow = append(grow, grow...)
printslice("grow", grow)
// append string to []bytes
bytes := append([]byte{1, 2, 3}, "foo"...)
print("bytes: len=", len(bytes), " cap=", cap(bytes), " data:")
for _, n := range bytes {
print(" ", n)
}
println()
}
func printslice(name string, s []int) {
print(name, ": len=", len(s), " cap=", cap(s), " data:")
for _, n := range s {
print(" ", n)
}
println()
}
func sum(l []int) int {
sum := 0
for _, n := range l {
sum += n
}
return sum
}
|