Original post

Is there a way to trap an empty interface?

I fetch data from Postgresql and populate a list. If the list is empty I want to redirect to another page. Here is my attempt (that not works):

    list := Get(query)

        switch list {
        case nil:
            returns []
                    fmt.Println("no result")
        default:
            returns [map[post_id:1 post_subject:Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...] map[post_id:2 post_subject:Vestibulum ante ipsum primis in faucibus orci luctus et ultrices]]
                    fmt.Println("show result")
        }

Hi, @Sibert, what doesn’t work? Are you getting an error when you build or when you use it? What’s the error?

The result is the exact the same regardless of empty or populated. No errors.

[] gives OK
[map[post_id:1] gives OK

A nil slice is not the same as an empty slice; the slice could be initialized but have no elements. Instead of:

switch list {
case nil:
    // ...

I recommend:

switch {
case len(list) == 0:
    // there are no results.
default:
    // there is at least 1 result
}

https://play.golang.org/p/btt2PPxoohf

invalid argument list (type interface {}) for len

If Get(query) returns the empty interface, and doesn’t return nil when there are no results, I’m not sure of the right way to do this. I would investigate refactoring that Get function to return a better type, but in the meantime, you could try:

import "reflect"

func isEmpty(v interface{}) bool {
    if v == nil {
        return true
    }
    switch v := v.(type) {
    case []interface{}:    // maybe test for some other types before falling back to reflection
        return len(v) == 0
    default:
        rv := reflect.ValueOf(v)
        switch rv.Kind() {
        case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
            return rv.Len() == 0
        }
        return false
    }
}

list := Get(query)

switch {
case isEmpty(list):
    // ...
default:
    // else
}

Will this be on right track or is it a dead end?

https://play.golang.org/p/EkCWHC80_k1

package main

import (
        "fmt"
)

func main() {

        list := map[string]string{"id": "kjh"}
        listempty := map[string]string{"id": ""}

        result1 := check(len(list["id"]))
        result2 := check(len(listempty["id"]))

        fmt.Println(result1)
        fmt.Println(result2)

}

func check(ok int) string {
        switch ok {
        case 0:
                return ("empty")
        default:
                return ("OK")
        }
}

@Sibert That checks if there are any key-value pairs in the map, but what I presume is a printed representation of list in your first post:

looks like a slice of maps, so checking the length of the individual map(s) won’t tell you if there are any maps.

I’ve tried to make reasonable guesses about what you’re trying to do based on the pseudo-code and panic messages but your latest example is significantly different than the assumptions I had at the beginning. If you’re trying to check the lengths of the actual maps, your latest Go Playground example will work, but if you’re still looking for something else, can you put that full example into a Go playground and/or some publicly accessible source control repository?

I wrote in my original question:

“I fetch data from Postgresql and populate a list. If the list is empty I want to redirect to another page.” In order to tell the user there is no data fetched.

There is TWO options I can think of:

  1. Query the database and check for empty result during the query.
  2. Check if the result of the query when returned.

In some other languages you can do both in a simple way, but Go makes it harder to achieve. For example both #1 and #2 could be done like If list.$linecount=0…

As Go is a different beast and I am a complete newbie, I have hard to understand why checking if the result of a query is empty or not could be simpler.

Something like ErrNoRows is returned by Scan when db.QueryRow but not a list generated by db.Query(…) for some reason.

The aim is that present “no data” for the user when searching and no records to show.

http://94.237.92.101:3030/mytopics

It is not the full example, but the essential parts

https://play.golang.org/p/XiaNyvS_Tf_q

Somewhere I have to check that the list contains no data. errNoRows does not work AFAIK.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.