在Golang中处理可选的布尔值

在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?

我无法理解如何解决自己的应用程序中当前遇到的问题。 p>

想象一下这个结构示例,该结构对传入的请求进行建模,并且该函数将来自该请求的字段放入数据库中。 p>

  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)
} 
  code>  
 
 

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

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.