简体   繁体   中英

Loop through slice of unknown length

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
}

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM