如何访问reflect.Value的底层结构?

问题描述 投票:0回答:1

如何从反射库访问reflect.Value(例如,time.Time)的底层(不透明)结构?

到目前为止,我一直在创建一个临时的 time.Time,获取它的 ValueOf,然后使用 Set() 将其复制出来。有没有办法直接访问原件asa time.Time?

go reflection
1个回答
0
投票

当您有一个代表

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.