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.

GoData Integrity

Code

gosnippet
28 lines
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

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.