golang设定值的时间。时间

时间:2014-06-06 14:14:07

标签: go

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

下面的编程工作的问题是我如何用time.Time类型像

这样做
    package main

     import (
       "fmt"
       "reflect"
      )

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

这很重要,因为我打算在通用结构

上使用它

我真的很感谢你对此的帮助

1 个答案:

答案 0 :(得分:14)

只需使用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)
}
相关问题