How to zip two arrays

Viewed 343

I start out with two arrays in a struct that I hand over to the template engine. The first array is a list of first names, the second array is a list of last names.

How do I get the Golang-template to print a list of full names?

What I have:

package main
import (
    "os"
    "text/template"
)
func main() {
    type Monty struct {
        FirstName [5]string
        LastName  [5]string
    }
    python := Monty{
        FirstName: [5]string{"John", "Eric", "Terry", "Terry", "Michael"},
        LastName:  [5]string{"Cleese", "Idle", "Gilliam", "Jones", "Palin"},
    }
    t := template.Must(template.New("t3").Parse(`
    {{ range .FirstName }}
      {{.}}
    {{ end }}
`))
    t.Execute(os.Stdout, python)
}

The expected out is

John Cleese
Eric Idle
Terry Gilliam
Terry Jones
Michael Palin

I have tried to use "index", "pipelines", and "range" and more.

1 Answers

If you are certain that the two arrays have the same length, you can do this:

 {{ range $index, $fname := .FirstName }}
      {{$fname}} {{index $.LastName $index}}
 {{ end }}
Related