英文:
Change identical fields in a nested structure
问题
我有一个嵌套结构。我想要更改所有名为"Text"的字段。
在这个例子中,"Text"出现在三个不同的层级中。如何优雅地迭代所有(任意)嵌套深度,并更改所有名为"Text"的字段呢?
("Text"字段始终是字符串类型。)
type First struct {
Text string `json:"text"`
Second Second `json:"second"`
}
type Second struct {
Text string `json:"text"`
Nested Nested `json:"nested"`
}
type Nested struct {
Text string `json:"text"`
}
英文:
I have a nested structure. I would like to change all fields which are called "Text" for example.
In this example "Text" is present in three different levels. How can I elegantly iterate over all (any) nesting depths and change all fields called "Text"?
("Text" - fields are always of type string.)
type First struct {
Text string `json:"text"`
Second Second `json:"second"`
}
type Second struct {
Text string `json:"text"`
Nested Nested `json:"nested"`
}
type Nested struct {
Text string `json:"text"`
}
答案1
得分: 1
如何优雅地迭代所有(任意)嵌套深度并更改所有名为“Text”的字段?
如果你认为反射是“优雅”的话,可以使用反射。
大多数人不认为反射是优雅的,所以真正的答案是“你不能”。
英文:
> How can I elegantly iterate over all (any) nesting depths and change all fields called "Text"?
If you consider reflection "elegant" than use reflection.
Most people do not consider reflection to be elegant, so the real answer would be "You cannot."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论