关于 go 布尔默认值问题

2021-10-28 17:21:37 +08:00
 imherer

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

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

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

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

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

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

697 次点击
所在节点    Go 编程语言
6 条回复
virusdefender
2021-10-28 17:22:36 +08:00
*bool
Cheivin
2021-10-28 17:22:50 +08:00
要不你考虑考虑*bool
imherer
2021-10-28 17:24:50 +08:00
@virusdefender
@Cheivin 感谢,可行
XTTX
2021-10-29 12:40:52 +08:00
// 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
2021-10-29 12:46:38 +08:00
@XTTX 这个是哪里的? 有原文链接没呢
XTTX
2021-10-29 13:37:07 +08:00
@imherer 这来自 ardanlab_service repo ,你在 github 里能搜到。强烈建议学习他的整个 repo 里的 pattern

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

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

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

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

© 2021 V2EX