实现说明
头尾窗口按长度收紧可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
first 2:、last 2:、head 10:。
常见问题
运行「头尾窗口按长度收紧」会打印什么?
整个文件跑完,输出行以 first 2:、last 2:、head 10: 这类前缀开头。
核心语句
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:]
}
代码示例
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])
}