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

关于 go 布尔默认值问题

  •  
  •   imherer · 2021-10-28 17:21:37 +08:00 · 690 次点击
    这是一个创建于 882 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假如有如下结构体(同时也对应数据库里的一张表)

    type Form struct {
      ID int `json:"id"`
      IsOk bool `json:"is_ok"`
      // 一些其他字段
    }
    

    假如我现在要修改这个 Form 的某些值,前端在做逻辑的时候只会向后端提交有修改的值

    因为 go bool 默认是 false ,当IsOk=false的时候我怎么知道这个值是前端传上来的还是是它的默认值呢

    同理intstring其实也有同样的问题,不过可以用特殊的字符规避掉

    大佬们有更换的解决办法吗

    virusdefender
        1
    virusdefender  
       2021-10-28 17:22:36 +08:00   ❤️ 1
    *bool
    Cheivin
        2
    Cheivin  
       2021-10-28 17:22:50 +08:00   ❤️ 1
    要不你考虑考虑*bool
    imherer
        3
    imherer  
    OP
       2021-10-28 17:24:50 +08:00
    @virusdefender
    @Cheivin 感谢,可行
    XTTX
        4
    XTTX  
       2021-10-29 12:40:52 +08:00   ❤️ 1
    // UpdateUser defines what information may be provided to modify an existing
    // User. All fields are optional so clients can send just the fields they want
    // changed. It uses pointer fields so we can differentiate between a field that
    // was not provided and a field that was provided as explicitly blank. Normally
    // we do not want to use pointers to basic types but we make exceptions around
    // marshalling/unmarshalling.
    type UpdateUser struct {
    Username *string `json:"username"`
    Email *string `json:"email" validate:"omitempty,email"`
    Password *string `json:"password"`
    PasswordConfirm *string `json:"passwordConfirm" validate:"omitempty,eqfield=Password"`
    }
    imherer
        5
    imherer  
    OP
       2021-10-29 12:46:38 +08:00
    @XTTX 这个是哪里的? 有原文链接没呢
    XTTX
        6
    XTTX  
       2021-10-29 13:37:07 +08:00   ❤️ 1
    @imherer 这来自 ardanlab_service repo ,你在 github 里能搜到。强烈建议学习他的整个 repo 里的 pattern
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1093 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:53 · PVG 02:53 · LAX 11:53 · JFK 14:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.