Home >Backend Development >Golang >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)
This function takes two integers and returns their sum. In the template, it can be used as follows:
{{index .Things (add $size -1)}}
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!