github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/reflect2/test/struct_test.go (about) 1 package test 2 3 import ( 4 "testing" 5 "github.com/v2pro/plz/reflect2" 6 "github.com/v2pro/plz/test" 7 "github.com/v2pro/plz/countlog" 8 "unsafe" 9 "github.com/v2pro/plz/test/must" 10 ) 11 12 func Test_struct(t *testing.T) { 13 type TestObject struct { 14 Field1 int 15 Field2 int 16 } 17 var pInt = func(val int) *int { 18 return &val 19 } 20 t.Run("New", testOp(func(api reflect2.API) interface{} { 21 valType := api.TypeOf(TestObject{}) 22 obj := valType.New() 23 obj.(*TestObject).Field1 = 20 24 obj.(*TestObject).Field2 = 100 25 return obj 26 })) 27 t.Run("PackEFace", test.Case(func(ctx *countlog.Context) { 28 valType := reflect2.TypeOf(TestObject{}) 29 ptr := valType.UnsafeNew() 30 must.Equal(&TestObject{}, valType.PackEFace(ptr)) 31 })) 32 t.Run("Indirect", test.Case(func(ctx *countlog.Context) { 33 valType := reflect2.TypeOf(TestObject{}) 34 must.Equal(TestObject{}, valType.Indirect(&TestObject{})) 35 })) 36 t.Run("SetIndex", testOp(func(api reflect2.API) interface{} { 37 valType := api.TypeOf(TestObject{}).(reflect2.StructType) 38 field1 := valType.FieldByName("Field1") 39 obj := TestObject{} 40 field1.Set(&obj, pInt(100)) 41 return obj 42 })) 43 t.Run("UnsafeSetIndex", test.Case(func(ctx *countlog.Context) { 44 valType := reflect2.TypeOf(TestObject{}).(reflect2.StructType) 45 field1 := valType.FieldByName("Field1") 46 obj := TestObject{} 47 field1.UnsafeSet(unsafe.Pointer(&obj), reflect2.PtrOf(100)) 48 must.Equal(100, obj.Field1) 49 })) 50 t.Run("GetIndex", testOp(func(api reflect2.API) interface{} { 51 obj := TestObject{Field1: 100} 52 valType := api.TypeOf(obj).(reflect2.StructType) 53 field1 := valType.FieldByName("Field1") 54 return field1.Get(&obj) 55 })) 56 t.Run("UnsafeGetIndex", test.Case(func(ctx *countlog.Context) { 57 obj := TestObject{Field1: 100} 58 valType := reflect2.TypeOf(obj).(reflect2.StructType) 59 field1 := valType.FieldByName("Field1") 60 value := field1.UnsafeGet(unsafe.Pointer(&obj)) 61 must.Equal(100, *(*int)(value)) 62 })) 63 }