vendredi 28 mai 2021

How to set the value of a field of type time.Time as time.Now() using reflect in Golang

I have a struct of type

type test struct {
    fname string
    time time.Time
}

I want to set the value of the field "time" as time.Now() using reflect package only.

I am creating a function something like this one:

func setRequestParam(arg interface{}, param string, value interface{}) {
    v := reflect.ValueOf(arg).Elem()
    f := v.FieldByName(param)
    if f.IsValid() {
        if f.CanSet() {
            if f.Kind() == reflect.String {
                f.SetString(value.(string))
                return
            } else if f.Kind() == reflect.Struct {
                f.Set(reflect.ValueOf(value))
            }
        }
    }
}

what I am trying to fix is this expression f.Set(reflect.ValueOf(value)), I am getting an error here.





Aucun commentaire:

Enregistrer un commentaire