gpt4 book ai didi

go - 如何以非手动方式更改所有结构标签的前缀?

转载 作者:IT王子 更新时间:2023-10-29 02:31:05 25 4
gpt4 key购买 nike

假设我有以下内容:

type My struct{
First string `xml:"first"`
Last string `xml:"name"`
...many more tags...
}

我想将所有标签的前缀更改为“mycustomtag”。我看过https://stackoverflow.com/a/42549826/522962但这描述了一种手动方式,您可以手动定义带有标签的第二个结构。我如何自动执行此操作?

例如我想以下面的内容结束,但由于有很多很多字段,我该怎么做才能不必手动完成?:

// how do I do the next part automagically????
func (m *My) MarshalJSON() ([]byte, error) {
type alias struct {
First string `mycustomtag:"first"`
Last string `mycustomtag:"name"`
...many more tags...
}
var a alias = alias(*m)
return json.Marshal(&a)
}

最佳答案

如果这不是在运行时,而是静态地修改您的代码源,您可以使用 fatih/gomodifytags .

参见“Writing a Go Tool to Parse and Modify Struct Tags

Struct field tags are an important part of encode/decode types, especially when using packages such as encoding/json.
However, modifying tags is repetitive, cumbersome and open to human errors.
We can make it easy to modify tags with an automated tool that is written for this sole purpose.

关于go - 如何以非手动方式更改所有结构标签的前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54209674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com