Slices Package Sort Compact And DeleteFunc
Use the slices package for Contains, Sort, Compact, Equal, Max, and DeleteFunc so common slice chores stop being hand-written loops.
Code
package main
import (
"fmt"
"slices"
)
func main() {
ids := []int{402, 17, 402, 5, 99}
// 查找与判断:Contains/Index 基于 comparable,无需手写循环
fmt.Println("contains 99:", slices.Contains(ids, 99))
fmt.Println("index of 402:", slices.Index(ids, 402))
// 原地排序后去除相邻重复
slices.Sort(ids)
ids = slices.Compact(ids)
fmt.Println("sorted unique:", ids)
// 泛型比较与最值:元素只需可比较
other := []int{5, 17, 99, 402}
fmt.Println("equal:", slices.Equal(ids, other))
fmt.Println("max:", slices.Max(ids), "min:", slices.Min(ids))
// 按谓词删除:原地移动元素,返回截短后的切片头
ids = slices.DeleteFunc(ids, func(v int) bool { return v < 50 })
fmt.Println("after delete:", ids)
}What the code does
Slices Package Sort Compact And DeleteFunc is built around the function main.
Applying it
The demo output is labeled (contains 99:, index of 402:, sorted unique:), so the printed output reads as a trace of the operations performed.
Statements that matter
ids = slices.DeleteFunc(ids, func(v int) bool { return v < 50 })
Interactive Tools for This Topic
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.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.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 Slices Package Sort Compact And DeleteFunc print when run?
- Invoke the file as-is — the `contains 99:`, `index of 402:`, `sorted unique:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.