Shikhar Tyagi
Shikhar Tyagi

Reputation: 257

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.

Upvotes: 0

Views: 1968

Answers (1)

icza
icza

Reputation: 417472

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}

Upvotes: 2

Related Questions