mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-04 02:57:46 +00:00
reflect: fix reflect.TyepAssert for structs
This commit is contained in:
committed by
deadprogram
parent
d04332d688
commit
b29edadf48
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
Reference in New Issue
Block a user