CodeNest

Slices and range loops

A slice is Go's growable list:

nums := []int{2, 4, 6}
nums = append(nums, 8)
fmt.Println(len(nums))     // 4

for i, n := range nums {   // index and value
    fmt.Println(i, n)
}

Use _ to ignore the index: for _, n := range nums.

Try it

Print the sum and the count of the numbers:

Sum: 20
Count: 4
Go unavailable
Running Go needs a server execution engine, which isn't configured on this deployment. You can still read the lesson and try the code locally.
Loading editor…

Press Ctrl/ + Enter or click Run to see the output here.