读取顶层结构标签

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

Read top level struct tags

问题

如何从Go中的结构字段中获取标签?我有一个嵌套的结构,我想将其作为参数传递给另一个函数,并在那里读取标签。我知道可以通过将其作为字段访问来实现,但我正在寻找一种方法来实现。

type MyStruct struct {
	Nested struct{} `bson:"nested"`
}

func main() {

	val := reflect.ValueOf(MyStruct{})
	val.Type().Field(0).Tag.Get("bson") // 我想避免这种方式
	
	val := reflect.ValueOf(MyStruct{}.Nested)
	val.Tag???
}
英文:

How to get the tags from a struct field in Go? I have a nested struct which I want to pass as an argument to another function and read the tags there. I know that by accessing it as a field is possible, but I am searching for a way to it.

type MyStruct struct {
	Nested struct{} `bson:"nested"`
}

func main() {

	val := reflect.ValueOf(MyStruct{})
	val.Type().Field(0).Tag.Get("bson") // I want to avoid this
	
	val := reflect.ValueOf(MyStruct{}.Nested)
	val.Tag???
}

答案1

得分: 1

你想要访问的标签属于MyStruct。如果你传递Nested字段的值,会创建一个完全与MyStruct分离的副本。无法确定传递的值是来自MyStruct的字段,还是来自另一个结构体,或者来自其他任何来源(例如复合字面量)。所以这是不可能的。

英文:

The tag you want to access belongs to MyStruct. If you pass the value of the Nested field, a copy is made which will be completely detached from MyStruct. There's no way to tell if the value passed originates from a field of MyStruct or from another struct, or from any other source (e.g. from a composite literal). So this is not possible.

huangapple
  • 本文由 发表于 2021年7月24日 20:24:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/68509946.html
匿名

发表评论

匿名网友

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

确定