slice_struct_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package tests
  2. import (
  3. "github.com/modern-go/reflect2"
  4. "testing"
  5. )
  6. func Test_slice_struct(t *testing.T) {
  7. var pInt = func(val int) *int {
  8. return &val
  9. }
  10. t.Run("SetIndex", testOp(func(api reflect2.API) interface{} {
  11. type TestObject struct {
  12. Field1 float64
  13. Field2 float64
  14. }
  15. obj := []TestObject{{}, {}}
  16. valType := api.TypeOf(obj).(reflect2.SliceType)
  17. valType.SetIndex(&obj, 0, &TestObject{1, 3})
  18. valType.SetIndex(&obj, 1, &TestObject{2, 4})
  19. return obj
  20. }))
  21. t.Run("SetIndex single ptr struct", testOp(func(api reflect2.API) interface{} {
  22. type TestObject struct {
  23. Field1 *int
  24. }
  25. obj := []TestObject{{}, {}}
  26. valType := api.TypeOf(obj).(reflect2.SliceType)
  27. valType.SetIndex(&obj, 0, &TestObject{pInt(1)})
  28. valType.SetIndex(&obj, 1, &TestObject{pInt(2)})
  29. return obj
  30. }))
  31. t.Run("SetIndex single chan struct", testOp(func(api reflect2.API) interface{} {
  32. type TestObject struct {
  33. Field1 chan int
  34. }
  35. obj := []TestObject{{}, {}}
  36. valType := api.TypeOf(obj).(reflect2.SliceType)
  37. valType.SetIndex(&obj, 0, &TestObject{})
  38. valType.SetIndex(&obj, 1, &TestObject{})
  39. return obj
  40. }))
  41. t.Run("SetIndex single func struct", testOp(func(api reflect2.API) interface{} {
  42. type TestObject struct {
  43. Field1 func()
  44. }
  45. obj := []TestObject{{}, {}}
  46. valType := api.TypeOf(obj).(reflect2.SliceType)
  47. valType.SetIndex(&obj, 0, &TestObject{})
  48. valType.SetIndex(&obj, 1, &TestObject{})
  49. return obj
  50. }))
  51. }