简体   繁体   中英

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.

You have to export the struct fields, else only the declaring package has access to them.

type test struct {
    Fname string
    Time  time.Time
}

With this change your setRequestParam() function works.

Testing it:

t := test{}
setRequestParam(&t, "Fname", "foo")
setRequestParam(&t, "Time", time.Now())
fmt.Printf("%+v\n", t)

Output (try it on the Go Playground ):

{Fname:foo Time:2009-11-10 23:00:00 +0000 UTC m=+0.000000001}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM