在结构体字段标签定义中引用常量是可能的吗?

huangapple go评论85阅读模式
英文:

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.UserTypeAdminconstants.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 and constants.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.

huangapple
  • 本文由 发表于 2021年10月16日 06:37:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/69591274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定