golang set value on time.Time

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

golang set value on 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").Set(reflect.ValueOf(time.Date(2023, 8, 14, 17, 34, 8, 0, time.UTC)))
	fmt.Println(n.N)
}

下面的程序可以工作,问题是如何在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").Set(reflect.ValueOf(time.Date(2023, 8, 14, 17, 34, 8, 0, time.UTC)))
	fmt.Println(n.N)
}

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

我非常感谢你的帮助。

英文:
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

答案1

得分: 15

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

package main

import (
	"fmt"
	"reflect"
	"time"
)

func main() {
    type t struct {
    	N time.Time
    }
    var n = t{time.Now()}
    fmt.Println(n.N)
    
    // 在未来创建一个时间戳
    ft := time.Now().Add(time.Second*3600)
    
    // 使用反射进行设置
    reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(ft))
    
    fmt.Println(n.N)
}

希望对你有所帮助!

英文:

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

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:

确定