Chemdream
Chemdream

Reputation: 627

Go Google Datastore nulls

I have datastore objects that look like:

created (timestamp)
guid (string)
details (string)
start (string)
end (string

Often, the details, start or end are NULL.

In Go, I am trying to do this:

    type Edge struct {
        created   time.Time
        details   string `datastore: "details,omitempty"`
        guid      string `datastore: "guid,omitempty"`
        start     string `datastore: "start,omitempty"`
        end       string `datastore: "end,omitempty"`
    }

    for t := client.Run(ctx, q); ; {
        var x Edge
        key, err := t.Next(&x)
        if err == iterator.Done {
            break
        }
        if err != nil {
            fmt.Printf("error caught: %v\n\n", err)
        }
        fmt.Printf("Key=%v\nEdge=%#v\n\n", key, x)
    }

The output error is always something like:

error caught: datastore: cannot load field "guid" into a "main.Edge": no such struct field

Key=/edges,4503602429165568
Edge=main.Edge{created:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, details:"", guid:"", start:"", end:""}

When I search for that key in the datastore console, I see that guid is a valid string.

GetAll gave me almost the same problem.

My questions are:

Thank you.

Upvotes: 1

Views: 1186

Answers (1)

icza
icza

Reputation: 417452

Two problems that stand out immediately:

  1. Struct fields must be exported, so start their names with capital letter.
  2. Your tag values are "invalid" (they don't follow the conventions). You must not leave a space between the key datastore: and the value "details,omitempty".

So use the following struct definition:

type Edge struct {
    Created time.Time `datastore:"created"`
    Details string    `datastore:"details,omitempty"`
    Guid    string    `datastore:"guid,omitempty"`
    Start   string    `datastore:"start,omitempty"`
    End     string    `datastore:"end,omitempty"`
}

See similar questions for the above-mentioned 2 problems:

golang mgo getting empty objects

Why struct fields are showing empty?

If a property in the Datastore is null, that's not a problem for a Go struct. In such case the corresponding struct field will be the zero-value of its type, which is the empty string "" in case of the string type. If you want to be able to differentiate between the Datastore null, Datastore "missing property" and the actual empty string "", you may change the field type to be a pointer (like *string), in which case the missing property and the null value will correspond to a nil pointer value, and an existing but empty string value will be a non-nil pointer to an empty string value.

Upvotes: 1

Related Questions