SortedFunc Sorts A Copy Leaving Original Intact

slices.SortedFunc returns a freshly sorted copy and leaves the original intact, so audit order survives every presentation sort.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"cmp"
	"fmt"
	"slices"
)

func main() {
	// 采集顺序是审计线索:original 必须保持不动
	original := []string{"tokyo", "amsterdam", "berlin", "chicago"}

	// slices.Values 把切片转成 iter.Seq;SortedFunc sorts a copy, leaving the original intact
	byLength := slices.SortedFunc(slices.Values(original), func(a, b string) int {
		return cmp.Compare(len(a), len(b))
	})
	fmt.Println("sorted copy:", byLength)
	fmt.Println("original:", original)

	// 对照:SortFunc 原地排序,调用方手里的切片被改写
	inPlace := slices.Clone(original)
	slices.SortFunc(inPlace, func(a, b string) int {
		return cmp.Compare(len(a), len(b))
	})
	fmt.Println("in place:", inPlace)
}

How it works

SortedFunc Sorts A Copy Leaving Original Intact reduces to the function main.

Using it

Signature: func main()

Key statements

return cmp.Compare(len(a), len(b))
  • The call that does the work: byLength := slices.SortedFunc(slices.Values(original), func(a, b string) int {

Interactive Tools for This Topic

FAQ

What does SortedFunc Sorts A Copy Leaving Original Intact print when run?
The script runs standalone; its 3 labeled outputs include `sorted copy:`, `original:`, `in place:`.