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.
Code
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
CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.