| 1 |
--- |
| 2 |
title: collections.Last |
| 3 |
description: Returns the last N elements of the given slice or string. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [last] |
| 9 |
returnType: 'any' |
| 10 |
signatures: [collections.Last N SLICE|STRING] |
| 11 |
aliases: [/functions/last] |
| 12 |
--- |
| 13 |
|
| 14 |
```go-html-template |
| 15 |
{{ slice "a" "b" "c" | last 1 }} → [c] |
| 16 |
{{ slice "a" "b" "c" | last 2 }} → [b c] |
| 17 |
``` |
| 18 |
|
| 19 |
Given that a string is in effect a read-only slice of bytes, this function can be used to return the specified number of bytes from the end of the string: |
| 20 |
|
| 21 |
```go-html-template |
| 22 |
{{ "abc" | last 1 }} → c |
| 23 |
{{ "abc" | last 2 }} → bc |
| 24 |
``` |
| 25 |
|
| 26 |
Note that a _character_ may consist of multiple _bytes_: |
| 27 |
|
| 28 |
```go-html-template |
| 29 |
{{ "Schön" | last 1 }} → n |
| 30 |
{{ "Schön" | last 2 }} → \xb6n |
| 31 |
{{ "Schön" | last 3 }} → ön |
| 32 |
``` |
| 33 |
|
| 34 |
To use the `collections.Last` function with a page collection: |
| 35 |
|
| 36 |
```go-html-template |
| 37 |
{{ range last 5 .Pages }} |
| 38 |
{{ .Render "summary" }} |
| 39 |
{{ end }} |
| 40 |
``` |
| 41 |
|
| 42 |
Set `N` to zero to return an empty slice: |
| 43 |
|
| 44 |
```go-html-template |
| 45 |
{{ $emptyPageCollection := last 0 .Pages }} |
| 46 |
``` |
| 47 |
|
| 48 |
Use `last` and [`where`][] together: |
| 49 |
|
| 50 |
```go-html-template |
| 51 |
{{ range where .Pages "Section" "articles" | last 5 }} |
| 52 |
{{ .Render "summary" }} |
| 53 |
{{ end }} |
| 54 |
``` |
| 55 |
|
| 56 |
[`where`]: /functions/collections/where/ |