douzhaochan6468 2018-04-12 19:43
浏览 113
已采纳

在Golang中处理可选的布尔值

I'm failing to understand how I can work around the problem I'm currently experiencing in my own application.

Imagine this example of a struct that models an incoming request and a function that puts the fields from that request into a database.

type NewBooleanRequest struct {
    RequiredString string `json:"requiredString"`
    OptionalBoolean bool `json:"maybeBoolean"`
}

func LogBooleanRequest(req NewBooleanRequest, db *sql.DB) {
    db.Exec("INSERT INTO log (booleanValue, stringValue) VALUES ($1, $2)", req.OptionalBoolean, req.RequiredString)
}

Now this obviously works fine if I know I will be given a value for all fields of my request model, but that's not a common requirement in reality. How do people generally model "optional" semantics for bool values given that bool has a zero value that is valid in essentially all contexts?

  • 写回答

1条回答 默认 最新

  • douzhong2954 2018-04-12 19:46
    关注

    This question isn't specific to booleans, it's common for all NULLable types. The simplest solution is to use a pointer (*bool in your example). There are also Nullable values for common types provided by the sql package. sql.NullBool would be the one you want in this case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作