V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Yooloo

如何对待 golang 的零值问题

  •  
  •   Yooloo · Nov 14, 2019 · 5755 views
    This topic created in 2357 days ago, the information mentioned may be changed or developed.
    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 replies    2019-12-01 06:21:41 +08:00
    reus
        1
    reus  
       Nov 14, 2019   ❤️ 1
    有什么问题?既然数据库是 nullable 类型,go 的类型自然也要是 nullable 的,要么是 *int,要么是 sql.NullInt64
    TypeErrorNone
        2
    TypeErrorNone  
       Nov 14, 2019
    楼上+1,针对 null 值可以用 sql 定义的接收
    imherer
        3
    imherer  
       Nov 14, 2019
    gin BindJSON 的时候,某个 int 类型的值为 required,但是这时候客户端又要传 0 怎么办?
    14v45mJPBYJW8dT7
        4
    14v45mJPBYJW8dT7  
       Nov 14, 2019
    gorm 设置为 not null 时,int 默认是 0 string 默认是""
    HarrisonZ
        5
    HarrisonZ  
       Nov 14, 2019
    In aws sdk, any type is a pointer
    xrlin
        6
    xrlin  
       Dec 1, 2019
    所以尽量不要用零值
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1108 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 18:22 · PVG 02:22 · LAX 11:22 · JFK 14:22
    ♥ Do have faith in what you're doing.