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
Release: 2024-11-04 12:59:29
Original
795 people have browsed it

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>
Copy after login

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>
Copy after login

is equivalent to:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template