Loop through slice of unknown length

Viewed 342

Below is a code sample to get started. The idea is I am making an API endpoint so I do not know the length of the slice I am to parse. How would I iterate through an array in Golang with an unknown length so that it does not error out "Index out of Bound" or crash?

package main

type Human struct {
  ID    int64
  Name  string
  email string
  alive bool
}

func main() {
  var human []Human

  // add the loop here
}
1 Answers

Thanks to @tkausl and @Cerise Limón

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }
}
Related