Go 和 Postgresql 中的十进制类型与 gorm

Ste*_*rer 2 database postgresql go go-gorm

所以我正在创建一个 API,我需要存储某些东西的价格。

我正在使用 gorm 和 gormigrate 进行数据库迁移。我只是想知道应该使用什么正确的类型来存储小数。我在某个地方发红,表示在存储货币时不应该使用浮点数。

type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price <what type should be here> `json:"price"`
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*rer 6

因此,根据@ain的建议,我使用了shopspring/decimal。但当我自动迁移时,它给了我一个错误。

事实证明,我只需要将类型设置为numeric使用 gorm 标签即可使其工作:

type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price decimal.Decimal `json:"price" gorm:"type:numeric"`
}
Run Code Online (Sandbox Code Playgroud)