-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices03.go
34 lines (24 loc) · 1 KB
/
slices03.go
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
/* RZFeeser | Alta3 Research
Exploring slices - length vs capacity */
package main
import "fmt"
func main() {
// create a length of 3 and capacity of 5
numbers := make([]int, 3, 5)
fmt.Println("numbers =", numbers) // 0 0 0 nil nil (nil values not shown)
fmt.Println("length =", len(numbers)) // 3
fmt.Println("capacity =", cap(numbers)) // 5
// This line will cause a runtime error index out of range [4] with length 3
//numbers[4] = 5
//Increasing the length from 3 to 5
numbers = numbers[0:5] // 0 0 0 0 0
// This line will no longer cause a runtime error
numbers[4] = 5 // 0 0 0 0 5
fmt.Println("Increasing length from 3 to 5")
fmt.Println("numbers =", numbers) // 0 0 0 0 5
fmt.Println("length =", len(numbers)) // 5
fmt.Println("capacity =", cap(numbers)) // 5
// just use append in most situations
numbers = append(numbers, 66, 777, 8888) // 0 0 0 0 5 66 777 8888
fmt.Println("numbers =", numbers)
}