reflect: fix reflect.TyepAssert for structs

This commit is contained in:
Damian Gryski
2026-04-02 13:49:26 -07:00
committed by deadprogram
parent d04332d688
commit b29edadf48
2 changed files with 47 additions and 1 deletions
+1 -1
View File
@@ -138,7 +138,7 @@ func TypeAssert[T any](v Value) (T, bool) {
var zero T
return zero, false
}
if !v.isIndirect() {
if !v.isIndirect() && v.typecode.Size() <= unsafe.Sizeof(uintptr(0)) {
return *(*T)(unsafe.Pointer(&v.value)), true
}
return *(*T)(v.value), true
+46
View File
@@ -924,6 +924,52 @@ func testTypeAssert[T comparable, V any](t *testing.T, val V, wantVal T, wantOk
}
}
func TestTypeAssertStruct(t *testing.T) {
type taStruct struct {
i int
b bool
}
var a any
// struct
a = taStruct{3, true}
if s, ok := a.(taStruct); ok {
if s.i != 3 || s.b != true {
t.Errorf("a.(S) failed: got s.i=%v, s.b=%v\n", s.i, s.b)
}
} else {
t.Errorf("a.(S) failed: got ok=false")
}
if s, ok := TypeAssert[taStruct](ValueOf(a)); ok {
if s.i != 3 || s.b != true {
t.Errorf("TypeAssert[S] failed: got s.i=%v, s.b=%v\n", s.i, s.b)
}
} else {
t.Errorf("TypeAssert[S] failed: got ok=false")
}
// struct ptr
a = &taStruct{3, true}
if s, ok := a.(*taStruct); ok {
if s.i != 3 || s.b != true {
t.Errorf("a.(*S) failed: got s.i=%v, s.b=%v\n", s.i, s.b)
}
} else {
t.Errorf("a.(*S) failed: got ok=false")
}
if s, ok := TypeAssert[*taStruct](ValueOf(a)); ok {
if s.i != 3 || s.b != true {
t.Errorf("TypeAssert[*S] failed: got s.i=%v, s.b=%v\n", s.i, s.b)
}
} else {
t.Errorf("TypeAssert[*S] failed: got ok=false")
}
}
type testTypeWithMethod struct{ val string }
func (v testTypeWithMethod) String() string { return v.val }