github.com/bobyang007/helper@v1.1.3/reflecth/set.go (about)

     1  package reflecth
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // MakeSettable make x settable.
     9  // It panics if CanAddr returns false for x.
    10  //
    11  // Deprecated: In any case it is bad practice.
    12  func MakeSettable(x reflect.Value) reflect.Value {
    13  	addr := x.UnsafeAddr()
    14  	return reflect.NewAt(x.Type(), unsafe.Pointer(addr)).Elem()
    15  }
    16  
    17  // Set assigns src to the value dst.
    18  // It is similar to dst.Set(src) but this function also allow to set private fields.
    19  // Primary reason for this is to avoid restriction with your own struct variable.
    20  // It panics if CanAddr returns false.
    21  // As in Go, x's value must be assignable to v's type.
    22  //
    23  // Deprecated: In any case it is bad practice to change private fields in 3rd party variables/classes.
    24  func Set(dst, src reflect.Value) {
    25  	if !dst.CanSet() {
    26  		dst = MakeSettable(dst)
    27  	}
    28  	dst.Set(src)
    29  	return
    30  }