package main
import (
"fmt"
"reflect"
)
func main() {
type t struct {
N int
}
var n = t{42}
fmt.Println(n.N)
reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(7)
fmt.Println(n.N)
}
下面的 prog 工作问题是我如何使用 time.Time 类型来做到这一点
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
type t struct {
N time.Time
}
var n = t{ time.Now() }
fmt.Println(n.N)
reflect.ValueOf(&n).Elem().FieldByName("N"). (what func) (SetInt(7) is only for int) // there is not SetTime
fmt.Println(n.N)
}
这很重要,因为我打算在通用结构上使用它
非常感谢你在这方面的帮助
最佳答案
只需调用 Set()
并使用您要设置的时间的 reflect.Value
即可:
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
type t struct {
N time.Time
}
var n = t{time.Now()}
fmt.Println(n.N)
//create a timestamp in the future
ft := time.Now().Add(time.Second*3600)
//set with reflection
reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(ft))
fmt.Println(n.N)
}
关于golang 按时设置值.Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24083932/