在Go语言中查找结构体的匿名字段的底层类型。

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

Find underlying anonymous field type for struct in Go

问题

我有这两个结构体:

type CustomTime struct {
    time.Time
}

type Events struct {
    Timestamp CustomTime
}

当我使用 reflect 获取 Events.Timestamp 字段时,我得到的是 CustomTime,我该如何获取实际的底层类型 time.Time

英文:

I have these two structs:

type CustomTime struct {
	time.Time
}

type Events struct {
	Timestamp CustomTime
}

When I reflect the field for Events.Timestamp, I get CustomTime; how can I get the actual underlying type which is time.Time?

答案1

得分: 1

这是一个Go Playground的示例,展示了如何访问匿名字段。

https://play.golang.org/p/yQULMVaQK0

基本上,一旦你有了结构体的值,你就可以从第0个字段获取Time值。

英文:

Here is a go playground example showing how you can access the anonymous field.

https://play.golang.org/p/yQULMVaQK0

Basically, once you have the value of the struct you should be able to get the Time value from field 0

huangapple
  • 本文由 发表于 2017年8月3日 00:15:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/45466015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定