CodeSampleX

Пример

github.com/imdario/mergo v0.3.8: WithAppendSlice

Проверенный пример — golang github.com/imdario/mergo v0.3.8: WithAppendSlice. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:20dcded235c34df3a0d15027cfac321303216258af9536722daa407689ad882a

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-06

Кейс

HOW
Цель
verify github.com/imdario/mergo.WithAppendSlice in pkg:golang/github.com/imdario/mergo@v0.3.8
Пакеты
Символы
  • github.com/imdario/mergo.WithAppendSlice
Создан
2026-09-06T04:22:59Z

Контракт

  1. mergo.WithAppendSlice appends source slice elements to destination slice in a struct
  2. mergo.WithAppendSlice appends slice values for matching keys in map types
  3. mergo.WithAppendSlice populates nil destination slices from source slices
  4. mergo.WithAppendSlice preserves destination slice order when appending multiple elements
  5. mergo.WithAppendSlice combines with WithOverride to update scalar fields while appending slice fields

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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: verify github.com/imdario/mergo.WithAppendSlice in pkg:golang/github.com/imdario/mergo@v0.3.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/imdario/mergo@v0.3.8
Demonstrate these symbols/APIs:
  - github.com/imdario/mergo.WithAppendSlice

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:6b4f814cc4c282e42a745667f977045783583cb9b9643e5bc2afe89f4a291c73","contract":["mergo.WithAppendSlice appends source slice elements to destination slice in a struct","mergo.WithAppendSlice appends slice values for matching keys in map types","mergo.WithAppendSlice populates nil destination slices from source slices","mergo.WithAppendSlice preserves destination slice order when appending multiple elements","mergo.WithAppendSlice combines with WithOverride to update scalar fields while appending slice fields"],"goal":"verify github.com/imdario/mergo.WithAppendSlice in pkg:golang/github.com/imdario/mergo@v0.3.8","kind":"HOW","packages":["pkg:golang/github.com/imdario/mergo@v0.3.8"],"schemaVersion":1,"symbols":["github.com/imdario/mergo.WithAppendSlice"]},"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/imdario/mergo@v0.3.8"],"schemaVersion":1,"subject":"pkg:golang/github.com/imdario/mergo@v0.3.8","symbols":["github.com/imdario/mergo.WithAppendSlice"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/imdario/mergo v0.3.8

require (
	github.com/stretchr/testify v1.12.1 // indirect
	gopkg.in/yaml.v2 v2.4.0 // indirect
)
go.sum
github.com/imdario/mergo v0.3.8 h1:CGgOkSJeqMRmt0D9XLWExdT4m4F1vd3FV3VPt+0VxkQ=
github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
main.go
package main

import (
	"fmt"

	"github.com/imdario/mergo"
)

type ServiceConfig struct {
	Name      string
	Endpoints []string
	Tags      []string
}

func main() {
	dst := ServiceConfig{
		Name:      "sample-service",
		Endpoints: []string{"https://example.com/v1"},
		Tags:      []string{"primary"},
	}

	src := ServiceConfig{
		Name:      "sample-service-v2",
		Endpoints: []string{"https://example.com/v2"},
		Tags:      []string{"v2-ready"},
	}

	// Merge src into dst using WithAppendSlice so slices are concatenated rather than kept or overwritten
	if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil {
		fmt.Printf("merge failed: %v\n", err)
		return
	}

	fmt.Printf("Service: %s\n", dst.Name)
	fmt.Printf("Endpoints: %v\n", dst.Endpoints)
	fmt.Printf("Tags: %v\n", dst.Tags)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/imdario/mergo.WithAppendSlice in pkg:golang/github.com/imdario/mergo@v0.3.8",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/imdario/mergo@v0.3.8"
  ],
  "symbols": [
    "github.com/imdario/mergo.WithAppendSlice"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"reflect"

	"github.com/imdario/mergo"
)

func main() {
	// Assertion 1: mergo.WithAppendSlice appends source slice elements to destination slice in a struct
	{
		type Config struct {
			Items []string
		}
		dst := Config{Items: []string{"first", "second"}}
		src := Config{Items: []string{"third", "fourth"}}

		if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: %v\n", err)
			os.Exit(1)
		}

		expected := []string{"first", "second", "third", "fourth"}
		if !reflect.DeepEqual(dst.Items, expected) {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected %v, got %v\n", expected, dst.Items)
			os.Exit(1)
		}
	}

	// Assertion 2: mergo.WithAppendSlice appends slice values for matching keys in map types
	{
		dst := map[string][]int{
			"scores": {10, 20},
		}
		src := map[string][]int{
			"scores": {30, 40},
		}

		if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: %v\n", err)
			os.Exit(1)
		}

		expected := []int{10, 20, 30, 40}
		if !reflect.DeepEqual(dst["scores"], expected) {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected %v, got %v\n", expected, dst["scores"])
			os.Exit(1)
		}
	}

	// Assertion 3: mergo.WithAppendSlice populates nil destination slices from source slices
	{
		type Config struct {
			Items []string
		}
		dst := Config{Items: nil}
		src := Config{Items: []string{"alpha", "beta"}}

		if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: %v\n", err)
			os.Exit(1)
		}

		expected := []string{"alpha", "beta"}
		if !reflect.DeepEqual(dst.Items, expected) {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected %v, got %v\n", expected, dst.Items)
			os.Exit(1)
		}
	}

	// Assertion 4: mergo.WithAppendSlice preserves destination slice order when appending multiple elements
	{
		type Sequence struct {
			Steps []int
		}
		dst := Sequence{Steps: []int{1, 2, 3}}
		src := Sequence{Steps: []int{4, 5, 6}}

		if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: %v\n", err)
			os.Exit(1)
		}

		expected := []int{1, 2, 3, 4, 5, 6}
		if !reflect.DeepEqual(dst.Steps, expected) {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected %v, got %v\n", expected, dst.Steps)
			os.Exit(1)
		}
	}

	// Assertion 5: mergo.WithAppendSlice combines with WithOverride to update scalar fields while appending slice fields
	{
		type Config struct {
			Name  string
			Ports []int
		}
		dst := Config{Name: "initial", Ports: []int{80}}
		src := Config{Name: "updated", Ports: []int{443}}

		if err := mergo.Merge(&dst, src, mergo.WithOverride, mergo.WithAppendSlice); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: %v\n", err)
			os.Exit(1)
		}

		if dst.Name != "updated" {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected name 'updated', got %q\n", dst.Name)
			os.Exit(1)
		}
		expectedPorts := []int{80, 443}
		if !reflect.DeepEqual(dst.Ports, expectedPorts) {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected ports %v, got %v\n", expectedPorts, dst.Ports)
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

Исходный сидер

аноним