Home >Backend Development >Golang >How to Iterate Through Parallel Arrays with Range and Index in Go Templates?

How to Iterate Through Parallel Arrays with Range and Index in Go Templates?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 12:59:29779browse

How to Iterate Through Parallel Arrays with Range and Index in Go Templates?

Iterating Through Parallel Arrays with Range and Index

How can we iterate through two parallel arrays with the same size and list items from both arrays concurrently using range?

The following code demonstrates an unsuccessful attempt:

<code class="go">{{range $i, $e := .First}}{{ $e }} - {{ index .Second $i }}{{end}}</code>

To address this challenge, we can utilize the predefined global template function, index. This function allows us to index the first argument with subsequent arguments, similar to how indexing works in Go.

<code class="go">index x 1 2 3</code>

is equivalent to:

<code class="go">x[1][2][3]</code>

However, within the range block, dot has been reassigned. To return to the original dot, we use the built-in template feature that sets $ initially to the data argument passed to Execute. Therefore, we can modify our code:

<code class="go">{{range $i, $e := .First}}{{$e}} - {{index $.Second $i}}{{end}}</code>

As an alternative to this, it may be cleaner to create a template function called zip that transforms multiple slices into a slice of value pairs.

The above is the detailed content of How to Iterate Through Parallel Arrays with Range and Index in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn