Home >Backend Development >Golang >How Do I Get the Last Element of a Go Slice in a Template?
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.
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!