export.go 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. // Copyright 2017, The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package cmp
  5. import (
  6. "reflect"
  7. "unsafe"
  8. )
  9. // retrieveUnexportedField uses unsafe to forcibly retrieve any field from
  10. // a struct such that the value has read-write permissions.
  11. //
  12. // The parent struct, v, must be addressable, while f must be a StructField
  13. // describing the field to retrieve. If addr is false,
  14. // then the returned value will be shallowed copied to be non-addressable.
  15. func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value {
  16. ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem()
  17. if !addr {
  18. // A field is addressable if and only if the struct is addressable.
  19. // If the original parent value was not addressable, shallow copy the
  20. // value to make it non-addressable to avoid leaking an implementation
  21. // detail of how forcibly exporting a field works.
  22. if ve.Kind() == reflect.Interface && ve.IsNil() {
  23. return reflect.Zero(f.Type)
  24. }
  25. return reflect.ValueOf(ve.Interface()).Convert(f.Type)
  26. }
  27. return ve
  28. }