Пример
github.com/google/go-cmp v0.7.0: Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps
Проверенный пример — golang github.com/google/go-cmp v0.7.0: Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps.…
sha256:c3fc112adf4e45343f486f011a096d85afb76a9347a03fa07505c99dc8caa5ca
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
linux 24 · ubuntu · glibc 2.39 x64 go
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-08-28 |
Кейс
HOW- Цель
- Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps
- Символы
-
- cmpopts.SortMaps
- cmpopts.SortSlices
- Создан
- 2026-08-28T06:31:58Z
Контракт
- assert cmp.Diff reports differences for permuted slices when cmpopts.SortSlices is omitted
- assert cmpopts.SortSlices equates slices containing identical elements in different order
- assert cmpopts.SortSlices sorts struct slices using custom less comparator
- assert cmpopts.SortMaps equates maps with identical key-value pairs
- assert cmpopts.SortSlices panics when provided an invalid less function signature
Файлы
- PROMPT.md
- csx.json
- go.mod
- go.sum
- spec.json
- src/sort.go
- test/main.go
Исходный код
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/github.com/google/go-cmp@v0.7.0
Demonstrate these symbols/APIs:
- cmpopts.SortMaps
- cmpopts.SortSlices
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:940127d4b25983cf55d68c471f7f29dfe007be53c8c70c82624baa7781eccfe3","contract":["assert cmp.Diff reports differences for permuted slices when cmpopts.SortSlices is omitted","assert cmpopts.SortSlices equates slices containing identical elements in different order","assert cmpopts.SortSlices sorts struct slices using custom less comparator","assert cmpopts.SortMaps equates maps with identical key-value pairs","assert cmpopts.SortSlices panics when provided an invalid less function signature"],"goal":"Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps","kind":"HOW","packages":["pkg:golang/github.com/google/go-cmp@v0.7.0"],"schemaVersion":1,"symbols":["cmpopts.SortMaps","cmpopts.SortSlices"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/google/go-cmp@v0.7.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/google/go-cmp@v0.7.0","symbols":["cmpopts.SortMaps","cmpopts.SortSlices"],"verifierAdapter":"golang@1"}
module codesamplex.dev/sample/gocmpext
go 1.24
require github.com/google/go-cmp v0.7.0
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
{
"schemaVersion": 1,
"goal": "Compare slices and maps irrespective of order using cmpopts.SortSlices and cmpopts.SortMaps",
"kind": "HOW",
"packages": [
"pkg:golang/github.com/google/go-cmp@v0.7.0"
],
"symbols": [
"cmpopts.SortMaps",
"cmpopts.SortSlices"
]
}
// Package sample demonstrates sorting slices and maps for order-independent comparison using go-cmp.
package sample
import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
// Item represents a structured entity with an ID and value.
type Item struct {
ID int
Name string
}
// DiffSlicesStrict compares two string slices strictly where element order matters.
func DiffSlicesStrict(a, b []string) string {
return cmp.Diff(a, b)
}
// DiffSlicesUnordered compares two string slices irrespective of element order using cmpopts.SortSlices.
func DiffSlicesUnordered(a, b []string) string {
return cmp.Diff(a, b, cmpopts.SortSlices(func(x, y string) bool {
return x < y
}))
}
// DiffItemsUnordered compares two Item slices irrespective of element order by sorting on Item.ID.
func DiffItemsUnordered(a, b []Item) string {
return cmp.Diff(a, b, cmpopts.SortSlices(func(x, y Item) bool {
return x.ID < y.ID
}))
}
// DiffMapsOrdered compares maps by sorting their keys using cmpopts.SortMaps.
func DiffMapsOrdered(a, b map[string]int) string {
return cmp.Diff(a, b, cmpopts.SortMaps(func(x, y string) bool {
return x < y
}))
}
// SortSlicesInvalid constructs a SortSlices option with an invalid function signature, which panics.
func SortSlicesInvalid() (panicked bool) {
defer func() {
if recover() != nil {
panicked = true
}
}()
// Invalid signature: unary function instead of binary (T, T) -> bool
_ = cmpopts.SortSlices(func(x string) bool {
return true
})
return false
}
package main
import (
"fmt"
"os"
"strings"
sample "codesamplex.dev/sample/gocmpext/src"
)
func fail(format string, args ...any) {
fmt.Printf(format+"\n", args...)
os.Exit(1)
}
func main() {
s1 := []string{"banana", "apple", "cherry"}
s2 := []string{"apple", "banana", "cherry"}
// Strict slice diff detects ordering difference
if d := sample.DiffSlicesStrict(s1, s2); d == "" {
fail("strict slice diff should report ordering difference")
}
// Unordered slice diff with cmpopts.SortSlices reports no difference
if d := sample.DiffSlicesUnordered(s1, s2); d != "" {
fail("cmpopts.SortSlices should consider permuted string slices equal, got diff:\n%s", d)
}
// Struct slice comparison with cmpopts.SortSlices
items1 := []sample.Item{{ID: 3, Name: "c"}, {ID: 1, Name: "a"}, {ID: 2, Name: "b"}}
items2 := []sample.Item{{ID: 1, Name: "a"}, {ID: 2, Name: "b"}, {ID: 3, Name: "c"}}
if d := sample.DiffItemsUnordered(items1, items2); d != "" {
fail("cmpopts.SortSlices should consider permuted struct slices equal, got diff:\n%s", d)
}
// Map comparison with cmpopts.SortMaps
m1 := map[string]int{"b": 2, "a": 1, "c": 3}
m2 := map[string]int{"a": 1, "b": 2, "c": 3}
if d := sample.DiffMapsOrdered(m1, m2); d != "" {
fail("cmpopts.SortMaps should evaluate equal maps as identical, got diff:\n%s", d)
}
// Map diff format with mismatch
m3 := map[string]int{"z": 10, "a": 1}
m4 := map[string]int{"a": 1, "z": 20}
diffMapMismatch := sample.DiffMapsOrdered(m3, m4)
if diffMapMismatch == "" || !strings.Contains(diffMapMismatch, "z") {
fail("expected diff output highlighting key mismatch 'z', got %q", diffMapMismatch)
}
// Invalid less signature panics at option construction
if panicked := sample.SortSlicesInvalid(); !panicked {
fail("cmpopts.SortSlices with invalid function signature must panic")
}
fmt.Println("CONTRACT PASS: cmpopts.SortSlices and cmpopts.SortMaps verified successfully")
}
Исходный сидер
аноним