CodeSampleX

샘플

github.com/spf13/cast v1.7.0: ToString, ToStringE, ToInt

검증된 샘플 — golang github.com/spf13/cast v1.7.0: ToString, ToStringE, ToInt. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:90db890a527aab17441d5ab3196e06544ca5570263d500a749559f8ace6ee5da

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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@1
2026-08-21

케이스

HOW
목표
verify pkg:golang/github.com/spf13/cast@v1.7.0
패키지
심벌
  • cast.ToString
  • cast.ToStringE
  • cast.ToInt
  • cast.ToIntE
  • cast.ToBool
  • cast.ToBoolE
  • cast.ToDuration
  • cast.ToDurationE
  • cast.ToStringSlice
  • cast.ToStringSliceE
  • cast.ToStringMapString
  • cast.ToStringMapStringE
생성일
2026-08-21T00:06:31Z

컨트랙트

  1. cast.ToString and cast.ToStringE convert numeric values, booleans, and byte slices to string representations
  2. cast.ToInt and cast.ToIntE safely parse numeric strings, booleans, and floats into integer values
  3. cast.ToBool and cast.ToBoolE parse string and numeric representations into boolean values
  4. cast.ToDuration and cast.ToDurationE parse formatted duration strings and numeric nanoseconds into time.Duration
  5. cast.ToStringSlice and cast.ToStringSliceE convert slice collections of arbitrary types into []string
  6. cast.ToStringMapString and cast.ToStringMapStringE convert map structures with arbitrary value types into map[string]string

파일

  • PROMPT.md
  • cast_sample.go
  • cast_sample_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json

소스 아티팩트 내려받기 (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 pkg:golang/github.com/spf13/cast@v1.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/spf13/cast@v1.7.0

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.
cast_sample.go
package sample

import (
	"time"

	"github.com/spf13/cast"
)

// SafeToString converts an arbitrary value to string, returning an error if conversion fails.
func SafeToString(val interface{}) (string, error) {
	return cast.ToStringE(val)
}

// ConvertToString converts an arbitrary value to string or returns empty string if invalid.
func ConvertToString(val interface{}) string {
	return cast.ToString(val)
}

// SafeToInt converts an arbitrary value to int, returning an error if conversion fails.
func SafeToInt(val interface{}) (int, error) {
	return cast.ToIntE(val)
}

// ConvertToInt converts an arbitrary value to int or returns 0 if invalid.
func ConvertToInt(val interface{}) int {
	return cast.ToInt(val)
}

// SafeToBool converts an arbitrary value to bool, returning an error if conversion fails.
func SafeToBool(val interface{}) (bool, error) {
	return cast.ToBoolE(val)
}

// ConvertToBool converts an arbitrary value to bool or returns false if invalid.
func ConvertToBool(val interface{}) bool {
	return cast.ToBool(val)
}

// SafeToDuration converts an arbitrary value to time.Duration, returning an error if conversion fails.
func SafeToDuration(val interface{}) (time.Duration, error) {
	return cast.ToDurationE(val)
}

// ConvertToDuration converts an arbitrary value to time.Duration or returns 0 if invalid.
func ConvertToDuration(val interface{}) time.Duration {
	return cast.ToDuration(val)
}

// SafeToStringSlice converts an arbitrary slice/interface to []string, returning an error if conversion fails.
func SafeToStringSlice(val interface{}) ([]string, error) {
	return cast.ToStringSliceE(val)
}

// ConvertToStringSlice converts an arbitrary slice/interface to []string or returns empty slice if invalid.
func ConvertToStringSlice(val interface{}) []string {
	return cast.ToStringSlice(val)
}

// SafeToStringMapString converts an arbitrary map/interface to map[string]string, returning an error if conversion fails.
func SafeToStringMapString(val interface{}) (map[string]string, error) {
	return cast.ToStringMapStringE(val)
}

// ConvertToStringMapString converts an arbitrary map/interface to map[string]string or returns empty map if invalid.
func ConvertToStringMapString(val interface{}) map[string]string {
	return cast.ToStringMapString(val)
}
cast_sample_test.go
package sample

import (
	"reflect"
	"testing"
	"time"

	"github.com/spf13/cast"
)

func TestToString(t *testing.T) {
	// Direct cast.ToString & cast.ToStringE
	str, err := cast.ToStringE(12345)
	if err != nil || str != "12345" {
		t.Fatalf("expected '12345', got %q, err: %v", str, err)
	}

	if s := cast.ToString(true); s != "true" {
		t.Fatalf("expected 'true', got %q", s)
	}

	if s := cast.ToString([]byte("hello")); s != "hello" {
		t.Fatalf("expected 'hello', got %q", s)
	}

	// Helper tests
	if s := ConvertToString(42); s != "42" {
		t.Fatalf("ConvertToString failed, got %q", s)
	}

	if _, err := SafeToString(struct{ Name string }{"test"}); err == nil {
		t.Fatal("expected error converting complex struct to string with ToStringE")
	}
}

func TestToInt(t *testing.T) {
	// Direct cast.ToInt & cast.ToIntE
	num, err := cast.ToIntE("100")
	if err != nil || num != 100 {
		t.Fatalf("expected 100, got %d, err: %v", num, err)
	}

	if n := cast.ToInt(true); n != 1 {
		t.Fatalf("expected 1 for true, got %d", n)
	}

	if n := cast.ToInt(123.45); n != 123 {
		t.Fatalf("expected 123 for float, got %d", n)
	}

	// Helper tests
	if n := ConvertToInt("50"); n != 50 {
		t.Fatalf("ConvertToInt failed, got %d", n)
	}

	if _, err := SafeToInt("not-a-number"); err == nil {
		t.Fatal("expected error converting non-numeric string with ToIntE")
	}
}

func TestToBool(t *testing.T) {
	// Direct cast.ToBool & cast.ToBoolE
	b, err := cast.ToBoolE("true")
	if err != nil || !b {
		t.Fatalf("expected true, got %v, err: %v", b, err)
	}

	b2, err := cast.ToBoolE("1")
	if err != nil || !b2 {
		t.Fatalf("expected true for '1', got %v, err: %v", b2, err)
	}

	b3, err := cast.ToBoolE(0)
	if err != nil || b3 {
		t.Fatalf("expected false for 0, got %v, err: %v", b3, err)
	}

	// Helper tests
	if !ConvertToBool("true") {
		t.Fatal("expected true for 'true'")
	}

	if _, err := SafeToBool("unrecognized-bool"); err == nil {
		t.Fatal("expected error converting invalid bool string with ToBoolE")
	}
}

func TestToDuration(t *testing.T) {
	// Direct cast.ToDuration & cast.ToDurationE
	d, err := cast.ToDurationE("5s")
	if err != nil || d != 5*time.Second {
		t.Fatalf("expected 5s, got %v, err: %v", d, err)
	}

	d2, err := cast.ToDurationE(5000000000) // nanoseconds
	if err != nil || d2 != 5*time.Second {
		t.Fatalf("expected 5s from int, got %v, err: %v", d2, err)
	}

	// Helper tests
	if res := ConvertToDuration("10m"); res != 10*time.Minute {
		t.Fatalf("ConvertToDuration failed, got %v", res)
	}

	if _, err := SafeToDuration("invalid-duration"); err == nil {
		t.Fatal("expected error converting invalid duration string with ToDurationE")
	}
}

func TestToStringSlice(t *testing.T) {
	// Direct cast.ToStringSlice & cast.ToStringSliceE
	input := []interface{}{"apple", 123, true}
	expected := []string{"apple", "123", "true"}

	slice, err := cast.ToStringSliceE(input)
	if err != nil || !reflect.DeepEqual(slice, expected) {
		t.Fatalf("expected %v, got %v, err: %v", expected, slice, err)
	}

	// Helper tests
	res := ConvertToStringSlice([]int{1, 2, 3})
	if !reflect.DeepEqual(res, []string{"1", "2", "3"}) {
		t.Fatalf("ConvertToStringSlice failed, got %v", res)
	}
}

func TestToStringMapString(t *testing.T) {
	// Direct cast.ToStringMapString & cast.ToStringMapStringE
	input := map[string]interface{}{
		"host": "localhost",
		"port": 8080,
	}
	expected := map[string]string{
		"host": "localhost",
		"port": "8080",
	}

	resMap, err := cast.ToStringMapStringE(input)
	if err != nil || !reflect.DeepEqual(resMap, expected) {
		t.Fatalf("expected %v, got %v, err: %v", expected, resMap, err)
	}

	// Helper tests
	helperMap := ConvertToStringMapString(input)
	if !reflect.DeepEqual(helperMap, expected) {
		t.Fatalf("ConvertToStringMapString failed, got %v", helperMap)
	}
}
csx.json
{"case":{"caseId":"case:sha256:3b08d92b7908060b2f295ad1b15f087b14d9bfd48c061648390577ed826e15e3","contract":["cast.ToString and cast.ToStringE convert numeric values, booleans, and byte slices to string representations","cast.ToInt and cast.ToIntE safely parse numeric strings, booleans, and floats into integer values","cast.ToBool and cast.ToBoolE parse string and numeric representations into boolean values","cast.ToDuration and cast.ToDurationE parse formatted duration strings and numeric nanoseconds into time.Duration","cast.ToStringSlice and cast.ToStringSliceE convert slice collections of arbitrary types into []string","cast.ToStringMapString and cast.ToStringMapStringE convert map structures with arbitrary value types into map[string]string"],"goal":"verify pkg:golang/github.com/spf13/cast@v1.7.0","kind":"HOW","packages":["pkg:golang/github.com/spf13/cast@v1.7.0"],"schemaVersion":1,"symbols":["cast.ToString","cast.ToStringE","cast.ToInt","cast.ToIntE","cast.ToBool","cast.ToBoolE","cast.ToDuration","cast.ToDurationE","cast.ToStringSlice","cast.ToStringSliceE","cast.ToStringMapString","cast.ToStringMapStringE"]},"contractCommand":["go","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/spf13/cast@v1.7.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/spf13/cast@v1.7.0","symbols":["cast.ToString","cast.ToStringE","cast.ToInt","cast.ToIntE","cast.ToBool","cast.ToBoolE","cast.ToDuration","cast.ToDurationE","cast.ToStringSlice","cast.ToStringSliceE","cast.ToStringMapString","cast.ToStringMapStringE"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/spf13/cast v1.7.0
go.sum
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/spf13/cast@v1.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/spf13/cast@v1.7.0"
  ]
}

오리진 시더

익명