github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/reflectx/set_value.go (about)

     1  package reflectx
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  func SetValue(rv reflect.Value, tpe reflect.Type, rightValue interface{}) error {
     9  	if rightValue == nil {
    10  		return nil
    11  	}
    12  
    13  	tpe = IndirectType(tpe)
    14  	rightValueType := IndirectType(reflect.TypeOf(rightValue))
    15  	if tpe != rightValueType {
    16  		panic(fmt.Errorf("%s cannot set %s", tpe.String(), rightValueType.String()))
    17  	}
    18  
    19  	if rv.IsValid() && rv.Kind() == reflect.Ptr && rv.IsNil() && rv.CanSet() {
    20  		rv.Set(reflect.New(tpe))
    21  	}
    22  
    23  	indirectRv := reflect.Indirect(rv)
    24  	if indirectRv.CanSet() {
    25  		indirectRv.Set(reflect.Indirect(reflect.ValueOf(rightValue)))
    26  	}
    27  
    28  	return nil
    29  }