CodeSampleX

サンプル

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. go 1.26 …

sha256:c3fc112adf4e45343f486f011a096d85afb76a9347a03fa07505c99dc8caa5ca

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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

コントラクト

  1. assert cmp.Diff reports differences for permuted slices when cmpopts.SortSlices is omitted
  2. assert cmpopts.SortSlices equates slices containing identical elements in different order
  3. assert cmpopts.SortSlices sorts struct slices using custom less comparator
  4. assert cmpopts.SortMaps equates maps with identical key-value pairs
  5. 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

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
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.
csx.json
{"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"}
go.mod
module codesamplex.dev/sample/gocmpext

go 1.24

require github.com/google/go-cmp v0.7.0
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
spec.json
{
  "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"
  ]
}
src/sort.go
// 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
}
test/main.go
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")
}

オリジンシーダー

匿名