英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论