slices.IsSorted Validates Ordering
Check ordering invariants with slices.IsSorted and IsSortedFunc before binary searching, so unsorted input is caught instead of producing wrong results.
Code
package main
import (
"fmt"
"slices"
"strings"
)
type Server struct {
Name string
Load int
}
func main() {
ids := []int{3, 7, 11, 19}
fmt.Println("ids sorted:", slices.IsSorted(ids))
// IsSortedFunc:按自定义键检查(名称升序)
servers := []Server{
{"api", 40},
{"billing", 90},
{"auth", 10},
}
byName := func(a, b Server) int { return strings.Compare(a.Name, b.Name) }
fmt.Println("servers sorted by name:", slices.IsSortedFunc(servers, byName))
// 二分查找前先保证有序:乱序数据会得到错误结果
slices.SortFunc(servers, byName)
fmt.Println("after sort:", slices.IsSortedFunc(servers, byName))
}Inside the snippet
Structurally, expect the function main and nothing else.
Caveats
- Entirely standard-library — copy it in and it runs.
Putting it to use
Entry signature: func main()
Look for the ids sorted:, servers sorted by name:, after sort: prefixes when the file runs; they tie each line to its step.
Core lines
byName := func(a, b Server) int { return strings.Compare(a.Name, b.Name) }
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does slices.IsSorted Validates Ordering print when run?
- No setup needed: run the file and look for labeled lines like `ids sorted:`, `servers sorted by name:`, `after sort:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.