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
Release: 2024-11-21 05:05:15
Original
380 people have browsed it

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

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

{{index .Things (subtract $size 1)}}
Copy after login

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!

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