Home >Backend Development >Golang >How Do I Get the Last Element of a Go Slice in a Template?

How Do I Get the Last Element of a Go Slice in a Template?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 05:05:15378browse

How Do I Get the Last Element of a Go Slice in a Template?

Obtaining the Last Element of a Slice in Go Templates

In Go templates, while you can easily determine the size of a slice using len, getting the last element can be tricky since indexing is zero-based.

Using a FuncMap

Rather than defining custom functions, Go templates provide the flexibility of extending functionality through FuncMaps. Let's create a "subtract" function that handles this scenario and similar arithmetic needs:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "subtract": func(a, b int) int { return a - b },
}).Parse(theTemplate)

In your template, you can now utilize this function as follows:

{{index .Things (subtract $size 1)}}

This expression would effectively retrieve the last element of the slice by subtracting 1 from its length to compensate for zero-based indexing.

The above is the detailed content of How Do I Get the Last Element of a Go Slice in a Template?. 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