2018-04-12 19:43
浏览 103


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?

图片转代码服务由CSDN问答提供 功能建议



  type NewBool​​eanRequest结构{
 RequiredString string`json:“ requiredString”`
 OptionalBoolean bool`json:“ maybeBoolean”`
func LogBooleanRequest(req  NewBool​​eanRequest,db * sql.DB){
 db.Exec(“插入日志(booleanValue,stringValue)VALUES($ 1,$ 2)”,req.OptionalBoolean,req.RequiredString)
  <  / pre> 

现在,如果我知道可以为我的请求模型的所有字段赋予一个值,那么这显然可以正常工作,但这在现实中并不常见。 假设 bool 的零值实际上在所有情况下都是有效的,人们通常如何为 bool 值建模“可选”语义?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题