Home > Backend Development > Golang > How to Distinguish Between Unset and Empty Values in Go Structs?

How to Distinguish Between Unset and Empty Values in Go Structs?

Susan Sarandon
Release: 2024-10-24 12:58:02
Original
885 people have browsed it

How to Distinguish Between Unset and Empty Values in Go Structs?

Distinguishing Between Unset and Empty Values in Go Structs

In Go, when defining structs, you may encounter the need to distinguish between values that are intentionally unset and values that are simply empty. This can be critical for database persistence and ensuring accurate data handling.

Consider the following example:

<code class="go">type Organisation struct {
    Category string
    Code     string
    Name     string
}</code>
Copy after login

Let's say you want to determine if the Category field was never set or was intentionally set as an empty string. Using pointers for fields (e.g., *string) will not solve this problem, as the zero value for a pointer is nil, which cannot distinguish between an unset and an empty value.

To address this, you can utilize a custom type such as sql.NullString from the database/sql package. It keeps track of the NULL state and allows you to differentiate between the following scenarios:

  • unset: NullString{String: "", Valid: false}
  • empty string: NullString{String: "", Valid: true}
  • non-empty string: NullString{String: "value", Valid: true}

During database scanning and parameter binding, the sql.NullString type handles the NULL state automatically.

For example, to scan into a NullString field:

<code class="go">err := db.QueryRow("SELECT category FROM organisations WHERE id = ?", id).Scan(&org.Category)</code>
Copy after login

To bind a NullString value to a database parameter:

<code class="go">_, err := db.Exec("INSERT INTO organisations (category) VALUES (?)", org.Category)</code>
Copy after login

This approach allows you to distinguish between unset and empty values and ensure accurate database persistence.

The above is the detailed content of How to Distinguish Between Unset and Empty Values in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template