CodeSampleX

サンプル

google.golang.org/protobuf v1.32.0: structpb.Value.AsInterface

検証済みサンプル — golang google.golang.org/protobuf v1.32.0: structpb.Value.AsInterface. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:69b95fc6c8188edd965df1850fdcc21dfead97392a37761d4a4a237963ca99c2

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

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 go linux 24 · ubuntu · glibc 2.39 x64 go go 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-01

ケース

HOW
ゴール
verify google.golang.org/protobuf/types/known/structpb.Value.AsInterface in pkg:golang/google.golang.org/protobuf@v1.32.0
パッケージ
シンボル
  • google.golang.org/protobuf/types/known/structpb.Value.AsInterface
環境
go
作成日
2026-09-01T06:38:22Z

コントラクト

  1. Value.AsInterface called on a nil receiver or an empty Value with nil Kind returns nil.
  2. Value.AsInterface unpacks primitive NullValue to nil, BoolValue to bool, NumberValue to float64, and StringValue to string.
  3. Value.AsInterface unpacks StructValue into map[string]interface{} and ListValue into []interface{}.
  4. Value.AsInterface recursively unpacks nested composite structures containing maps, slices, primitives, and nulls into native Go types.
  5. structpb.NewValue converts Go integer, unsigned integer, and float types to NumberValue which unpack to float64 via AsInterface, while unsupported types like int8, int16, channels, and funcs return errors.

ファイル

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • value_as_interface_test.go

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

ソース

NOTES.md
# Protocol Buffers structpb Value.AsInterface Dynamic Value Unpacking

This sample verifies the unpacking behavior of `google.golang.org/protobuf/types/known/structpb.Value.AsInterface` in `google.golang.org/protobuf@v1.32.0`.

## Verified Behaviors and Contract

1. **Nil Receiver and Kind Safety**:
   - Calling `AsInterface()` on a nil `*structpb.Value` pointer returns `nil` safely without panicking.
   - Calling `AsInterface()` on an empty `&structpb.Value{}` with a `nil` Kind returns `nil`.
   - Calling `AsInterface()` on a `NullValue` returns `nil`.

2. **Primitive Type Unpacking**:
   - `BoolValue` unpacks to native Go `bool` (`true` or `false`).
   - `NumberValue` unpacks to native Go `float64`.
   - `StringValue` unpacks to native Go `string`.

3. **Composite Structures Unpacking**:
   - `StructValue` unpacks recursively to `map[string]interface{}`. An empty `StructValue` unpacks to an empty `map[string]interface{}{}`.
   - `ListValue` unpacks recursively to `[]interface{}`. An empty `ListValue` unpacks to an empty `[]interface{}{}`.

4. **Recursive Unpacking**:
   - Complex nested hierarchical structures composed of maps, lists, strings, numbers, booleans, and nulls are recursively converted to equivalent Go `map[string]interface{}` and `[]interface{}` trees.

5. **Type Support and Numeric Normalization**:
   - `structpb.NewValue` supports Go integer types (`int`, `int32`, `int64`), unsigned integers (`uint`, `uint32`, `uint64`), and float types (`float32`, `float64`), normalizing them all to `float64` upon calling `AsInterface()`.
   - Unsupported Go types such as `int8`, `int16`, `uint8`, `uint16`, `complex64`, channels, and functions return an error when passed to `structpb.NewValue`.
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 google.golang.org/protobuf/types/known/structpb.Value.AsInterface in pkg:golang/google.golang.org/protobuf@v1.32.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.32.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/structpb.Value.AsInterface
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:f3fa537f41ff0b74cada5466e713f2e75bcfbb40d1981c645c337eaca59bc7ad","contract":["Value.AsInterface called on a nil receiver or an empty Value with nil Kind returns nil.","Value.AsInterface unpacks primitive NullValue to nil, BoolValue to bool, NumberValue to float64, and StringValue to string.","Value.AsInterface unpacks StructValue into map[string]interface{} and ListValue into []interface{}.","Value.AsInterface recursively unpacks nested composite structures containing maps, slices, primitives, and nulls into native Go types.","structpb.NewValue converts Go integer, unsigned integer, and float types to NumberValue which unpack to float64 via AsInterface, while unsupported types like int8, int16, channels, and funcs return errors."],"goal":"verify google.golang.org/protobuf/types/known/structpb.Value.AsInterface in pkg:golang/google.golang.org/protobuf@v1.32.0","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.32.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/structpb.Value.AsInterface"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.32.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.32.0","symbols":["google.golang.org/protobuf/types/known/structpb.Value.AsInterface"],"verifierAdapter":"golang@1"}
go.mod
module example.com/structpbvalue

go 1.22

require google.golang.org/protobuf v1.32.0
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/structpb.Value.AsInterface in pkg:golang/google.golang.org/protobuf@v1.32.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.32.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/structpb.Value.AsInterface"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
value_as_interface_test.go
package structpbvalue_test

import (
	"reflect"
	"testing"

	"google.golang.org/protobuf/types/known/structpb"
)

// TestValueAsInterface_NilReceiverAndNilKind verifies that calling AsInterface on a nil pointer
// or an empty Value struct with nil Kind safely returns nil without panicking.
func TestValueAsInterface_NilReceiverAndNilKind(t *testing.T) {
	var nilValue *structpb.Value
	if got := nilValue.AsInterface(); got != nil {
		t.Fatalf("expected (*structpb.Value)(nil).AsInterface() to be nil, got %#v (%T)", got, got)
	}

	emptyValue := &structpb.Value{}
	if got := emptyValue.AsInterface(); got != nil {
		t.Fatalf("expected empty Value with nil Kind to return nil from AsInterface(), got %#v (%T)", got, got)
	}

	nullKindVal := structpb.NewNullValue()
	if got := nullKindVal.AsInterface(); got != nil {
		t.Fatalf("expected NewNullValue().AsInterface() to return nil, got %#v (%T)", got, got)
	}
}

// TestValueAsInterface_Primitives verifies that primitive Value kinds (NullValue, BoolValue,
// NumberValue, StringValue) unpack into their respective native Go types.
func TestValueAsInterface_Primitives(t *testing.T) {
	// BoolValue -> bool
	vBoolTrue := structpb.NewBoolValue(true)
	if got, ok := vBoolTrue.AsInterface().(bool); !ok || !got {
		t.Fatalf("expected bool true, got %#v (%T)", vBoolTrue.AsInterface(), vBoolTrue.AsInterface())
	}

	vBoolFalse := structpb.NewBoolValue(false)
	if got, ok := vBoolFalse.AsInterface().(bool); !ok || got {
		t.Fatalf("expected bool false, got %#v (%T)", vBoolFalse.AsInterface(), vBoolFalse.AsInterface())
	}

	// NumberValue -> float64
	vNum := structpb.NewNumberValue(42.5)
	if got, ok := vNum.AsInterface().(float64); !ok || got != 42.5 {
		t.Fatalf("expected float64 42.5, got %#v (%T)", vNum.AsInterface(), vNum.AsInterface())
	}

	vZero := structpb.NewNumberValue(0)
	if got, ok := vZero.AsInterface().(float64); !ok || got != 0.0 {
		t.Fatalf("expected float64 0.0, got %#v (%T)", vZero.AsInterface(), vZero.AsInterface())
	}

	// StringValue -> string
	vStr := structpb.NewStringValue("hello protobuf")
	if got, ok := vStr.AsInterface().(string); !ok || got != "hello protobuf" {
		t.Fatalf("expected string 'hello protobuf', got %#v (%T)", vStr.AsInterface(), vStr.AsInterface())
	}

	vEmptyStr := structpb.NewStringValue("")
	if got, ok := vEmptyStr.AsInterface().(string); !ok || got != "" {
		t.Fatalf("expected empty string '', got %#v (%T)", vEmptyStr.AsInterface(), vEmptyStr.AsInterface())
	}
}

// TestValueAsInterface_StructValue verifies that StructValue unpacks into a native map[string]interface{}.
func TestValueAsInterface_StructValue(t *testing.T) {
	rawMap := map[string]interface{}{
		"host":    "localhost",
		"port":    float64(8080),
		"enabled": true,
	}

	st, err := structpb.NewStruct(rawMap)
	if err != nil {
		t.Fatalf("NewStruct failed: %v", err)
	}

	vStruct := structpb.NewStructValue(st)
	got := vStruct.AsInterface()

	gotMap, ok := got.(map[string]interface{})
	if !ok {
		t.Fatalf("expected map[string]interface{}, got %T", got)
	}

	if !reflect.DeepEqual(rawMap, gotMap) {
		t.Fatalf("mismatch in unpacked struct map:\nwant: %#v\ngot:  %#v", rawMap, gotMap)
	}

	// Empty StructValue
	emptySt, err := structpb.NewStruct(nil)
	if err != nil {
		t.Fatalf("NewStruct(nil) failed: %v", err)
	}
	emptyVal := structpb.NewStructValue(emptySt)
	gotEmpty := emptyVal.AsInterface()
	if gotEmptyMap, ok := gotEmpty.(map[string]interface{}); !ok || len(gotEmptyMap) != 0 {
		t.Fatalf("expected empty map[string]interface{}, got %#v (%T)", gotEmpty, gotEmpty)
	}
}

// TestValueAsInterface_ListValue verifies that ListValue unpacks into a native []interface{}.
func TestValueAsInterface_ListValue(t *testing.T) {
	rawSlice := []interface{}{
		"first",
		float64(100),
		true,
		nil,
	}

	list, err := structpb.NewList(rawSlice)
	if err != nil {
		t.Fatalf("NewList failed: %v", err)
	}

	vList := structpb.NewListValue(list)
	got := vList.AsInterface()

	gotSlice, ok := got.([]interface{})
	if !ok {
		t.Fatalf("expected []interface{}, got %T", got)
	}

	if !reflect.DeepEqual(rawSlice, gotSlice) {
		t.Fatalf("mismatch in unpacked list slice:\nwant: %#v\ngot:  %#v", rawSlice, gotSlice)
	}

	// Empty ListValue
	emptyList, err := structpb.NewList(nil)
	if err != nil {
		t.Fatalf("NewList(nil) failed: %v", err)
	}
	emptyVal := structpb.NewListValue(emptyList)
	gotEmpty := emptyVal.AsInterface()
	if gotEmptySlice, ok := gotEmpty.([]interface{}); !ok || len(gotEmptySlice) != 0 {
		t.Fatalf("expected empty []interface{}, got %#v (%T)", gotEmpty, gotEmpty)
	}
}

// TestValueAsInterface_DeeplyNestedStructures verifies recursive conversion of deeply nested
// hierarchical structures with mixed maps, slices, and primitive values.
func TestValueAsInterface_DeeplyNestedStructures(t *testing.T) {
	nestedInput := map[string]interface{}{
		"name": "sample-cluster",
		"id":   float64(42),
		"tags": []interface{}{
			"prod",
			"east",
			map[string]interface{}{
				"meta":    "datacenter",
				"rack":    float64(12),
				"active":  true,
				"missing": nil,
			},
		},
		"config": map[string]interface{}{
			"retries": float64(3),
			"timeout": float64(30),
			"endpoints": []interface{}{
				"127.0.0.1:8080",
				"127.0.0.1:8081",
			},
		},
	}

	v, err := structpb.NewValue(nestedInput)
	if err != nil {
		t.Fatalf("NewValue failed for nested structure: %v", err)
	}

	got := v.AsInterface()
	if !reflect.DeepEqual(nestedInput, got) {
		t.Fatalf("AsInterface failed to recursively unpack nested structure:\nwant: %#v\ngot:  %#v", nestedInput, got)
	}
}

// TestValueAsInterface_SupportedNumericTypes verifies supported Go numeric types
// (int, int32, int64, uint, uint32, uint64, float32, float64) convert via NewValue and unpack to float64.
func TestValueAsInterface_SupportedNumericTypes(t *testing.T) {
	testCases := []struct {
		name     string
		input    interface{}
		expected float64
	}{
		{"int", int(10), 10.0},
		{"int32", int32(40), 40.0},
		{"int64", int64(50), 50.0},
		{"uint", uint(60), 60.0},
		{"uint32", uint32(90), 90.0},
		{"uint64", uint64(100), 100.0},
		{"float32", float32(3.14), float64(float32(3.14))},
		{"float64", float64(2.718), 2.718},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			v, err := structpb.NewValue(tc.input)
			if err != nil {
				t.Fatalf("NewValue(%v) failed: %v", tc.input, err)
			}
			got := v.AsInterface()
			f, ok := got.(float64)
			if !ok {
				t.Fatalf("expected float64 from AsInterface(), got %T (%#v)", got, got)
			}
			if f != tc.expected {
				t.Fatalf("expected %v, got %v", tc.expected, f)
			}
		})
	}
}

// TestValueAsInterface_UnsupportedTypesError verifies structpb.NewValue returns an error for
// unsupported Go numeric types (int8, int16, uint8, uint16), channels, and functions.
func TestValueAsInterface_UnsupportedTypesError(t *testing.T) {
	unsupportedValues := []interface{}{
		int8(10),
		int16(20),
		uint8(30),
		uint16(40),
		complex64(1 + 2i),
		make(chan int),
		func() {},
	}

	for _, val := range unsupportedValues {
		if _, err := structpb.NewValue(val); err == nil {
			t.Fatalf("expected NewValue to return error for unsupported type %T, got nil", val)
		}
	}
}

オリジンシーダー

匿名