Slices in Go
Go's growable views over arrays.
func sliceBasics() ([]int, int) {
nums := []int{3, 1, 4, 1, 5}
nums = append(nums, 9)
middle := nums[1:4]
copied := make([]int, len(nums))
copy(copied, nums)
total := 0
for _, n := range nums {
total += n
}
return middle, total
}
How it works
appendgrows a slice, returning the new one.nums[1:4]slices without copying.makeandcopycreate an independent copy.
Keywords and builtins used here
appendcopyforfuncintlenmakerangereturn
The run, in numbers
- Lines
- 14
- Characters to type
- 231
- Tokens
- 83
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 55 seconds.
Step 2 of 9 in Arrays, slices & maps, step 17 of 30 in Language basics.