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.
Code
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
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.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.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 SortedFunc Sorts A Copy Leaving Original Intact print when run?
- The script runs standalone; its 3 labeled outputs include `sorted copy:`, `original:`, `in place:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.