github.com/wfusion/gofusion@v1.1.14/common/utils/inspect/field_go116.go (about)

     1  //go:build go1.16 && !go1.18
     2  // +build go1.16,!go1.18
     3  
     4  // Inspired by github.com/chenzhuoyu/go-inspect
     5  
     6  package inspect
     7  
     8  import (
     9  	"reflect"
    10  )
    11  
    12  // FieldByName locates a field with name.
    13  func FieldByName(v reflect.Value, name string) (Field, bool) {
    14  	if fv, ok := v.Type().FieldByName(name); !ok {
    15  		return Field{}, false
    16  	} else {
    17  		return newField(v, fv), true
    18  	}
    19  }
    20  
    21  // FieldAt locates a field with index.
    22  func FieldAt(v reflect.Value, idx int) (Field, bool) {
    23  	if idx < 0 || idx >= v.NumField() {
    24  		return Field{}, false
    25  	} else {
    26  		return newField(v, v.Type().Field(idx)), true
    27  	}
    28  }
    29  
    30  func SetField(obj interface{}, fieldName string, val interface{}) {
    31  	mustOk(FieldByName(derefValue(reflect.ValueOf(obj)), fieldName)).(Field).Set(reflect.ValueOf(val))
    32  }
    33  
    34  func GetField(obj interface{}, fieldName string) (r interface{}) {
    35  	r = mustOk(FieldByName(derefValue(reflect.ValueOf(obj)), fieldName)).(Field).Get().Interface()
    36  	return
    37  }