safe_field.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package reflect2
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. type safeField struct {
  7. reflect.StructField
  8. }
  9. func (field *safeField) Offset() uintptr {
  10. return field.StructField.Offset
  11. }
  12. func (field *safeField) Name() string {
  13. return field.StructField.Name
  14. }
  15. func (field *safeField) PkgPath() string {
  16. return field.StructField.PkgPath
  17. }
  18. func (field *safeField) Type() Type {
  19. panic("not implemented")
  20. }
  21. func (field *safeField) Tag() reflect.StructTag {
  22. return field.StructField.Tag
  23. }
  24. func (field *safeField) Index() []int {
  25. return field.StructField.Index
  26. }
  27. func (field *safeField) Anonymous() bool {
  28. return field.StructField.Anonymous
  29. }
  30. func (field *safeField) Set(obj interface{}, value interface{}) {
  31. val := reflect.ValueOf(obj).Elem()
  32. val.FieldByIndex(field.Index()).Set(reflect.ValueOf(value).Elem())
  33. }
  34. func (field *safeField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) {
  35. panic("unsafe operation is not supported")
  36. }
  37. func (field *safeField) Get(obj interface{}) interface{} {
  38. val := reflect.ValueOf(obj).Elem().FieldByIndex(field.Index())
  39. ptr := reflect.New(val.Type())
  40. ptr.Elem().Set(val)
  41. return ptr.Interface()
  42. }
  43. func (field *safeField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer {
  44. panic("does not support unsafe operation")
  45. }