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)
}
The prog below works the question is how do I do this with time.Time type like
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)
}
This is important because I plan to use it on generic struct
I really appreciate your help on this
Simply call Set()
with a reflect.Value
of the time you want to set:
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)
}