How to Check if a `sql.Null[Type]` Field is Valid in Go Templates?

Linda Hamilton
Release: 2024-10-28 02:36:31
Original
414 people have browsed it

How to Check if a `sql.Null[Type]` Field is Valid in Go Templates?

Testing Valid Fields in Go Templates

In Go's database/sql package, Null[Type] structs assist in mapping database values with potential nulls into code. Determining whether a struct field is null, i.e., its Valid property is false, can be challenging.

To display a SQL field, use the .Value property:

<code class="go">{{ .MyStruct.MyField.Value }}</code>
Copy after login

When requiring more complex comparisons, testing the validity of the field becomes important. Using if with .Value alone results in errors if .MyField is not Valid.

Attempts to test the existence of a valid field using and and or template functions are also unsuccessful. The evaluation does not terminate early even if the result is clear from the first argument.

Instead, consider using nested if blocks:

<code class="go">{{if $.MyStruct.MyField}}
    {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}
{{end}}</code>
Copy after login

Alternatively, the with block can be employed, but it modifies the current template context:

<code class="go">{{range .SomeSlice}}
    {{with $.MyStruct.MyField}}
        {{if eq .Value .}}selected="selected"{{end}}
    {{end}}
{{/range}}</code>
Copy after login

Note that sql.NullXX types are non-nil structs. To determine if their Value method will return a non-nil value, check their Valid field:

<code class="go">{{if $.MyStruct.MyField.Valid}}
    {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}
{{end}}</code>
Copy after login

The above is the detailed content of How to Check if a `sql.Null[Type]` Field is Valid in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!