typestar

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

  1. append grows a slice, returning the new one.
  2. nums[1:4] slices without copying.
  3. make and copy create an independent copy.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 9 in Arrays, slices & maps, step 17 of 30 in Language basics.

← Previous Next →

Slices in other languages