如何对待 golang 的零值问题

2019-11-14 15:43:07 +08:00
 KaynW
type User struct {
  gorm.Model
  Name string
  Age  *int `gorm:"default:18"`
}

gorm 中为了保存零值只能这么写

type Req struct {
    Gender  *int     `json:"gender" binding:"exists"`
}

gin 中为了 BindJSON 零值时不出错也只能写成这样,有没有什么解决办法😶

5224 次点击
所在节点    Go 编程语言
6 条回复
reus
2019-11-14 15:57:24 +08:00
有什么问题?既然数据库是 nullable 类型,go 的类型自然也要是 nullable 的,要么是 *int,要么是 sql.NullInt64
TypeErrorNone
2019-11-14 17:10:01 +08:00
楼上+1,针对 null 值可以用 sql 定义的接收
imherer
2019-11-14 17:25:45 +08:00
gin BindJSON 的时候,某个 int 类型的值为 required,但是这时候客户端又要传 0 怎么办?
rimutuyuan
2019-11-14 17:27:39 +08:00
gorm 设置为 not null 时,int 默认是 0 string 默认是""
HarrisonZ
2019-11-14 17:46:28 +08:00
In aws sdk, any type is a pointer
xrlin
2019-12-01 06:21:41 +08:00
所以尽量不要用零值

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/619562

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX