access_field.go 543 B

1234567891011121314151617
  1. package utils
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. // AccessField can used to access unexported field of a struct
  7. // valueType must be the exact type of the field or it will panic
  8. func AccessField[valueType any](obj any, fieldName string) *valueType {
  9. field := reflect.ValueOf(obj).Elem().FieldByName(fieldName)
  10. if field.Type() != reflect.TypeOf(*new(valueType)) {
  11. panic("field type: " + field.Type().String() + ", valueType: " + reflect.TypeOf(*new(valueType)).String())
  12. }
  13. v := (*valueType)(unsafe.Pointer(field.UnsafeAddr()))
  14. return v
  15. }