英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论