【问题标题】:How to set the value of a field of type time.Time as time.Now() using reflect in Golang如何使用 Golang 中的反射将 time.Time 类型的字段的值设置为 time.Now()
【发布时间】:2021-05-28 17:03:07
【问题描述】:

我有一个类型的结构

type test struct {
    fname string
    time time.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)),我在这里遇到错误。

【问题讨论】:

  • 你试过什么?你有什么问题?给我们看minimal reproducible example
  • @icza 我已经更新了问题
  • 这是什么背景?你必须使用反射吗?
  • 是的,实际上,我有很多这样的结构,它们有这个共同的字段时间,需要更新,我写了一个处理所有这些结构的通用函数,在那个函数里面我设置了公共字段参数的值
  • @ShikharTyagi 我仍然不确定我是否理解上下文,但我认为使用所有这些结构类型通用的接口可能比使用反射更可取。

标签: go struct reflection


【解决方案1】:

您必须导出结构字段,否则只有声明包可以访问它们。

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}

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多