Home >Backend Development >Golang >How to Distinguish Properly Between Not Set vs. Empty Values in Go?

How to Distinguish Properly Between Not Set vs. Empty Values in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 05:26:02532browse

How to Distinguish Properly Between Not Set vs. Empty Values in Go?

Distinguishing Properly Between Not Set vs. Empty Values

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn