The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
Yooloo

如何对待 golang 的零值问题

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