英文:
Is it possible to reference constants in struct field tag definitions?
问题
我有一个数据库和JSON模型,它们使用结构字段注释来实现各种目的,比如指定枚举类型、验证可接受的值等。
一个数据库模型的例子:
type QRCode struct {
Algorithm string `json:"algorithm" gorm:"type:enum('hmac-sha3-256-v1')" validate:"oneof=hmac-sha3-256-v1"`
PublicCode []byte `json:"token" gorm:"size:32" validate:"len=32"`
UserType string `json:"user_type" gorm:"type:enum('admin','member')" validate:"one_of=admin member"`
gorm.Model
}
所以在这种情况下,有几个不同的常量:
- 公钥大小,在
constants.QRCodePublicCodeLength
中定义 - 算法,在
constants.QRCodeAlgorithmV1
中定义 - 用户类型,在
constants.UserTypeAdmin
和constants.UserTypeMember
中定义
如果能够将这些常量嵌入到字段标签中,那么就可以真正实现一切的真相来源,但我不知道在Go语言中是否可能实现。
我能在结构字段标签定义中使用常量吗?
英文:
I have database and JSON models which use struct field annotation for various purposes, namely specifying enumerations, which values are acceptable for validations, etc.
A database model example:
type QRCode struct {
Algorithm string `json:"algorithm" gorm:"type:enum('hmac-sha3-256-v1')" validate:"oneof=hmac-sha3-256-v1"`
PublicCode []byte `json:"token" gorm:"size:32" validate:"len=32"`
UserType string `json:"user_type" gorm:"type:enum('admin','member')" validate:"one_of=admin member"`
gorm.Model
}
So in this case, there are a few different constants:
- public key size, which I have in
constants.QRCodePublicCodeLength
- algorithm, which I have in
constants.QRCodeAlgorithmV1
- user type, which I have in
constants.UserTypeAdmin
andconstants.UserTypeMember
It would be very nice to be able to embed these constants in the field tags so that there is truly one source of truth for everything, but I don't know if this is possible in Go.
Can I use constants in struct field tag definitions?
答案1
得分: 3
在结构字段标签定义中可以使用常量吗?
不,这是不可能的。
英文:
> Can I use constants in struct field tag definitions?
No, this is not possible.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论