Home >Backend Development >Golang >How to Distinguish Properly Between Not Set vs. Empty Values in Go?
When working with structs in Go, it can be crucial to differentiate between values that have never been set and those that are simply empty, such as empty strings.
Consider the following struct:
<code class="go">type Organisation struct { Category string Code string Name string }</code>
To distinguish between categories that have never been set and those that are blank, one approach might be to use pointers to strings:
<code class="go">type Organisation struct { Category *string Code *string Name *string }</code>
However, the zero value for a string in Go is an empty string, meaning it's not possible to distinguish between the two cases.
When dealing with databases, it's important to separate between NULL and empty strings. For this purpose, the database/sql package offers the sql.NullString type:
<code class="go">type NullString struct { String string Valid bool // Valid is true if String is not NULL }</code>
By scanning into this type and using it as a query parameter, the database/sql package manages the NULL state for you, effectively distinguishing between unset and empty values.
The above is the detailed content of How to Distinguish Properly Between Not Set vs. Empty Values in Go?. For more information, please follow other related articles on the PHP Chinese website!