mercredi 4 juillet 2018

Golang template and testing for Valid fields

In Go's database/sql package, there are a bunch of Null[Type] structs that help map database values (and their possible nulls) into code. I'm trying to figure out how to test whether a struct field is null, or in other words, when its Valid property is false.

The recommended way to print a SQL field is to use the .Value property, like this:

<div></div>

This works great.

But suppose I have something slightly more complicated, where I need to test the value against something else, for example:

<select name="y">
   
       <option value="" selected="selected"></option>
   
</select>

As it happens, this works great, too, unless .MyField is not Valid, in which case I get the error, "error calling eq: invalid type for comparison". The error makes sense, because Go can't compare a nil Field against another value (or something like that).

I would have thought the 'easy' solution would be to test first whether the Value is nil, and then compare it against what I need, like this:

<select name="y">
   
       <option value="" selected="selected"></option>
   
</select>

In this case, I get the same "error calling eq: invalid type for comparison". I guess that means .MyField "exists" even though the value of .MyField is not Valid. So, then I tried a half dozen other versions, mostly with the same error, for example:

<select name="y">
   
       <option value="" selected="selected"></option>
   
</select>

At this point, I'm realizing I really don't understand how to test for the existence of a valid field at all. I'd appreciate any help you might have.

Thanks.

Aucun commentaire:

Enregistrer un commentaire