Skip to content

Conversation

@Akkadius
Copy link
Member

@Akkadius Akkadius commented Jun 1, 2025

Summary:

  • Fixes a panic: reflect: Field index out of bounds when dumping structs that embed other structs (i.e. promoted fields).
  • Replaces incorrect use of t.Field(i) with reflect.VisibleFields(t) + FieldByIndex, which safely handles embedded/promoted fields.

Before:

for i := range reflect.VisibleFields(t) {
    field := t.Field(i) // ❌ may panic

After:

for _, field := range reflect.VisibleFields(t) {
    fieldVal := v.FieldByIndex(field.Index) // ✅ safe

Test added:
TestPanicOnVisibleFieldsIndexMismatch — reproduces panic with embedded struct and confirms resolution.

Test Before

=== RUN   TestPanicOnVisibleFieldsIndexMismatch
--- FAIL: TestPanicOnVisibleFieldsIndexMismatch (0.00s)
panic: reflect: Field index out of bounds [recovered]
	panic: reflect: Field index out of bounds

goroutine 35 [running]:
testing.tRunner.func1.2({0x100b11d40, 0x100b59130})
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/testing/testing.go:1632 +0x1bc
testing.tRunner.func1()
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/testing/testing.go:1635 +0x334
panic({0x100b11d40?, 0x100b59130?})
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/runtime/panic.go:785 +0x124
reflect.(*structType).Field(0x1479499f8?, 0x0?)
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/reflect/type.go:1116 +0x164
reflect.(*rtype).Field(0x100b59e38?, 0x14000144210?)
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/reflect/type.go:749 +0x50
github.com/goforj/godump.printValue(0x14000144210, {0x100b2d0e0?, 0x140001401e0?, 0x10090831c?}, 0x0, 0x14000175e78)
	/Users/cmiles/code/godump/godump.go:220 +0x1038
github.com/goforj/godump.writeDump(0x14000144210, {0x1400011af48, 0x1, 0x1400011af08?})
	/Users/cmiles/code/godump/godump.go:168 +0xc4
github.com/goforj/godump.DumpStr({0x1400011af48, 0x1, 0x1})
	/Users/cmiles/code/godump/godump.go:83 +0x94
github.com/goforj/godump.TestPanicOnVisibleFieldsIndexMismatch(0x14000134820?)
	/Users/cmiles/code/godump/godump_test.go:502 +0x68
testing.tRunner(0x14000134820, 0x100b57b98)
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/testing/testing.go:1690 +0xe4
created by testing.(*T).Run in goroutine 1
	/Users/cmiles/go/pkg/mod/golang.org/[email protected]/src/testing/testing.go:1743 +0x314

Test After

=== RUN   TestPanicOnVisibleFieldsIndexMismatch
--- PASS: TestPanicOnVisibleFieldsIndexMismatch (0.00s)
PASS

Process finished with the exit code 0

@Akkadius Akkadius merged commit 9d59ba2 into main Jun 1, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants