golang设定值的时间.时间

use*_*287 8 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)
}
Run Code Online (Sandbox Code Playgroud)

下面的编程工作的问题是如何用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)
}
Run Code Online (Sandbox Code Playgroud)

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

我真的很感谢你的帮助

Not*_*fer 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)
}
Run Code Online (Sandbox Code Playgroud)