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.

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改