I'm failing to understand how I can work around the problem I'm 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?
Optional binding The code let booleanValue = booleanValue returns false if booleanValue is nil and the if block does not execute. If booleanValue is not nil , this code defines a new variable named booleanValue of type Bool (instead of an optional, Bool? ).
Nil is not a Bool. phoneyDev: The error states that the Bool? has not been unwrapped. That's what optional chaining does.
A nullable boolean has three possible values, and boolean logic cannot be applied to it. Therefor a nullable boolean isn't really a boolean; it's a three-value enumeration with bizarre semantics. @Adrian: Of course. And the entire purpose of a string is to store a sequence of zero or more characters.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
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.
Beside the accepted answer, I found this interesting library https://github.com/guregu/null that can deal with nullable value pretty well. It's very useful to declare API request params without messing with sql
library on the server routing (which is not so relevant).
For your case, you can write your request like:
type NewBooleanRequest struct {
RequiredString string `json:"requiredString"`
OptionalBoolean null.Bool `json:"maybeBoolean"`
}
request := NewBooleanRequest {
RequiredString: "Your string",
OptionalBoolean: null.BoolFrom(false)
}
if request.OptionalBoolean.Valid {
fmt.Println(request.OptionalBoolean.Bool) // Print "false"
} else {
fmt.Println("request.OptionalBoolean is NULL")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With