Head Tail Windows Clamp To Slice Length

Take head and tail windows of at most n items with clamping, and see that the windows remain views into the same backing array.

GoData Integrity

Code

gosnippet
29 lines
package main

import "fmt"

// head returns at most n leading items; tail returns at most n trailing items.
func head[T any](items []T, n int) []T {
	n = min(n, len(items))
	return items[:n]
}

func tail[T any](items []T, n int) []T {
	n = min(n, len(items))
	return items[len(items)-n:]
}

func main() {
	logs := []string{"boot", "config", "ready", "request", "shutdown"}

	fmt.Println("first 2:", head(logs, 2))
	fmt.Println("last 2: ", tail(logs, 2))

	// n beyond the length clamps to the whole slice, never panics
	fmt.Println("head 10:", head(logs, 10))
	fmt.Println("tail 10:", tail(logs, 10))

	// windows are views into the same backing array
	view := head(logs, 2)
	fmt.Println("view shares backing:", &view[0] == &logs[0])
}

The shape of this snippet — Head Tail Windows Clamp To Slice Length

The moving piece across this file is the function main.

Points of care

  • The platform ships every API in the file, so setup is zero.

Applying it

The entry-point signature is func main()

Output lines are prefixed (first 2:, last 2:, head 10:), so each label points back to the step that produced it.

Statements that matter

func head[T any](items []T, n int) []T {
	n = min(n, len(items))
	return items[:n]
}
func tail[T any](items []T, n int) []T {
	n = min(n, len(items))
	return items[len(items)-n:]
}

Interactive Tools for This Topic

FAQ

What does Head Tail Windows Clamp To Slice Length print when run?
Execute the whole file; each printed line is prefixed with a label like `first 2:`, `last 2:`, `head 10:`.