Home > Backend Development > Golang > How Can I Access the Last Element of a Go Slice in a Template Without Custom Functions?

How Can I Access the Last Element of a Go Slice in a Template Without Custom Functions?

Mary-Kate Olsen
Release: 2024-11-19 11:01:03
Original
609 people have browsed it

How Can I Access the Last Element of a Go Slice in a Template Without Custom Functions?

Retrieving the Last Element of a Slice in a Go Template

Question:

In a Go template, it's possible to get the size of a slice using len .Things and index it using index .Things 4. However, trying to index the last element using index .Things $size gives an error because indexing is zero-based. Is there an arithmetic solution without resorting to custom function definitions?

Answer:

While Go templates don't offer arithmetic operations natively, you can extend their functionality using a FuncMap. Here's how to add an "add" function:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "add": func(a, b int) int { return a + b },
}).Parse(theTemplate)
Copy after login

This function takes two integers and returns their sum. In the template, it can be used as follows:

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

This will return the element at index $size - 1, effectively getting the last element of the slice.

The above is the detailed content of How Can I Access the Last Element of a Go Slice in a Template Without Custom Functions?. 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