如何从反射库访问reflect.Value(例如,time.Time)的底层(不透明)结构?
到目前为止,我一直在创建一个临时的 time.Time,获取它的 ValueOf,然后使用 Set() 将其复制出来。有没有办法直接访问原件asa time.Time?
当您有一个代表
reflect.Value
类型值的 time.Time
时,您可以在 Interface()
上使用 reflect.Value
方法来获取 interface{}
形式的值,然后执行类型断言将其转换回time.Time
。
以下是通常将持有
reflect.Value
的 time.Time
转换回 time.Time
的方法:
package main
import (
"fmt"
"reflect"
"time"
)
type MyStruct struct {
Timestamp time.Time
Name string
}
func main() {
// Create a MyStruct value.
s := MyStruct{
Timestamp: time.Now(),
Name: "Test",
}
// Get the reflect.Value of the MyStruct value.
val := reflect.ValueOf(s)
// Access the Timestamp field.
timeField := val.FieldByName("Timestamp")
// Use Interface() to get an interface{} value, then do a type assertion
// to get the underlying time.Time.
underlyingTime, ok := timeField.Interface().(time.Time)
if !ok {
fmt.Println("Failed to get the underlying time.Time")
return
}
fmt.Println("Underlying time.Time:", underlyingTime)
}