如何使用反射在Golang中将类型为time.Time的字段值设置为time.Now()?

huangapple go评论81阅读模式
英文:

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

问题

我有一个类型为test的结构体:

type test struct {
    fname string
    time  time.Time
}

我想要使用reflect包将字段"time"的值设置为time.Now()

我正在创建一个类似下面这样的函数:

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))
            }
        }
    }
}

我试图修复的是这个表达式f.Set(reflect.ValueOf(value)),我在这里遇到了一个错误。

英文:

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.

答案1

得分: 2

你必须导出结构体字段,否则只有声明该结构体的包才能访问它们。

type test struct {
    Fname string
    Time  time.Time
}

通过这个改变,你的 setRequestParam() 函数就可以工作了。

测试一下:

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

输出结果(在 Go Playground 上尝试):

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

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}

huangapple
  • 本文由 发表于 2021年5月29日 01:03:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/67742945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定