go - Golang 中逗号分隔字段的结构标签

标签 go struct

假设我有一个像这样的结构:

type MyType struct {
    A, B string
}

我可以在这些字段上添加标签吗?显然,我可以将每个字段放在自己的行中。我只是好奇是否可以以原始格式标记字段。

最佳答案

是的,您可以,但您不能标记各个字段。来自Language Reference :

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration

所以你可以说

type MyType struct {
  A, B string `my_tag`
}

但这最终会导致 AB 都被标记为 my_tag。对于必须常见的用例(JSON、Protobuf 等),这不是您想要的。

关于go - Golang 中逗号分隔字段的结构标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793302/

相关文章:

json - 是否可以重写未知 json 结构中的字符串?

xml - 制作 xml 以在 golang 后的 http 中发送

unit-testing - 无法在 GoLand IDE 内的测试套件中运行单个测试?

c# - 有关结构实现接口(interface)时发生的情况的详细信息

go - go/ast 包中的 Doc 和 Comment 有什么区别?

go - 在Go项目中访问静态文件

c - 将变量设置为 0 时出现段错误

mongodb - 如何使用自定义结构在 mongo 中进行搜索?

c - 将结构放入共享内存

c - 正确使用结构数组