golang set value on time.Time

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

golang set value on time.Time

问题

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. )
  7. func main() {
  8. type t struct {
  9. N time.Time
  10. }
  11. var n = t{time.Now()}
  12. fmt.Println(n.N)
  13. reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(time.Date(2023, 8, 14, 17, 34, 8, 0, time.UTC)))
  14. fmt.Println(n.N)
  15. }

下面的程序可以工作,问题是如何在time.Time类型上实现类似的操作:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. )
  7. func main() {
  8. type t struct {
  9. N time.Time
  10. }
  11. var n = t{time.Now()}
  12. fmt.Println(n.N)
  13. reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(time.Date(2023, 8, 14, 17, 34, 8, 0, time.UTC)))
  14. fmt.Println(n.N)
  15. }

这很重要,因为我计划在通用结构上使用它。

我非常感谢你的帮助。

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. type t struct {
  8. N int
  9. }
  10. var n = t{42}
  11. fmt.Println(n.N)
  12. reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(7)
  13. fmt.Println(n.N)
  14. }

The prog below works the question is how do I do this with time.Time type like

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. )
  7. func main() {
  8. type t struct {
  9. N time.Time
  10. }
  11. var n = t{ time.Now() }
  12. fmt.Println(n.N)
  13. reflect.ValueOf(&n).Elem().FieldByName("N"). (what func) (SetInt(7) is only for int) // there is not SetTime
  14. fmt.Println(n.N)
  15. }

This is important because I plan to use it on generic struct

I really appreciate your help on this

答案1

得分: 15

只需使用要设置的时间的reflect.Value调用Set()函数:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. )
  7. func main() {
  8. type t struct {
  9. N time.Time
  10. }
  11. var n = t{time.Now()}
  12. fmt.Println(n.N)
  13. // 在未来创建一个时间戳
  14. ft := time.Now().Add(time.Second*3600)
  15. // 使用反射进行设置
  16. reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(ft))
  17. fmt.Println(n.N)
  18. }

希望对你有所帮助!

英文:

Simply call Set() with a reflect.Value of the time you want to set:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. )
  7. func main() {
  8. type t struct {
  9. N time.Time
  10. }
  11. var n = t{time.Now()}
  12. fmt.Println(n.N)
  13. //create a timestamp in the future
  14. ft := time.Now().Add(time.Second*3600)
  15. //set with reflection
  16. reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(ft))
  17. fmt.Println(n.N)
  18. }

huangapple
  • 本文由 发表于 2014年6月6日 22:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/24083932.html
匿名

发表评论

匿名网友

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

确定