如何从反射库中访问反射的基础(opaque)结构(例如,时间。时间)?

到目前为止,我一直在创建一个临时时间。时间,将其拿到值,然后使用set()将其复制。有没有办法直接作为时间访问原件?

分析解答

当您具有代表time.Time类型值的reflect.Value时,可以使用reflect.Value上的Interface()方法将值作为interface{}获取,然后进行类型的断言将其转换回time.Time

这是您通常会将time.Timetime.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)
}