V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
KaynW
V2EX  ›  Go 编程语言

如何对待 golang 的零值问题

  •  
  •   KaynW · 2019-11-14 15:43:07 +08:00 · 5203 次点击
    这是一个创建于 1597 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type User struct {
      gorm.Model
      Name string
      Age  *int `gorm:"default:18"`
    }
    

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

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

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

    6 条回复    2019-12-01 06:21:41 +08:00
    reus
        1
    reus  
       2019-11-14 15:57:24 +08:00   ❤️ 1
    有什么问题?既然数据库是 nullable 类型,go 的类型自然也要是 nullable 的,要么是 *int,要么是 sql.NullInt64
    TypeErrorNone
        2
    TypeErrorNone  
       2019-11-14 17:10:01 +08:00
    楼上+1,针对 null 值可以用 sql 定义的接收
    imherer
        3
    imherer  
       2019-11-14 17:25:45 +08:00
    gin BindJSON 的时候,某个 int 类型的值为 required,但是这时候客户端又要传 0 怎么办?
    rimutuyuan
        4
    rimutuyuan  
       2019-11-14 17:27:39 +08:00
    gorm 设置为 not null 时,int 默认是 0 string 默认是""
    HarrisonZ
        5
    HarrisonZ  
       2019-11-14 17:46:28 +08:00
    In aws sdk, any type is a pointer
    xrlin
        6
    xrlin  
       2019-12-01 06:21:41 +08:00
    所以尽量不要用零值
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2887 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 11:24 · PVG 19:24 · LAX 04:24 · JFK 07:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.