Go alternative for python loop.last

If the list is not empty, then the Python snippet prints a semicolon following the last item. You can achieve the same result in Go by surrounding the range with an if to check to see if there's at least one element in the slice and printing the ; outside of the loop.

{{if $hosts}}{{range $host := $hosts}}
{{$host}}
{{ end }} ;{{end}}

This snippet works because you are adding to the end of the last item. A more general solution requires a custom template function. Here's an example function:

func last(v interface{}, i int) (bool, error) {
  rv := reflect.ValueOf(v)
  if rv.Kind() != reflect.Slice {
    return false, errors.New("not a slice")
  }
  return rv.Len()-1 == i, nil
}

and here's how to use it in the template:

{{range $i, $host := $hosts }}
{{$host}}{{if last $hosts $i}} ;{{end}}
{{ end }}

I posted an a working example of the custom function to the playground.