如何检查空数组(结构数组)

A mySQL Query function returns an array of rows witch is defined as

type Row []interface{}

I would like to check if the returned array is empty, but I get a runtime panic:

s := fmt.Sprintf("select id, secret, shortname from beehives where shortname = '%s'", beehive)

rows, res, err := database.Query(s)
if err == nil {
    if len(rows) != 1 {

The expression len(rows) seems to cause the runtime panic if rows is empty.

How can I check for an empty array? I tried also rows == nil, which also panics.

It looks like you could use QueryRow, since that query is expected to return only one row.

QueryRow executes a query that is expected to return at most one row. QueryRow always return a non-nil value. Errors are deferred until Row's Scan method is called.

In this case, if there is no row, the ErrNoRows occurs, but is deferred until a .Scan occurs.

ErrNoRows is returned by Scan when QueryRow doesn't return a row. In such a case, QueryRow returns a placeholder *Row value that defers this error until a Scan.

So what you want to do is something like:

var id int
var secret string
var shortname string
err := db.QueryRow("SELECT ...").Scan(&id, &secret, &shortname)
switch {
    case err == sql.ErrNoRows:
        log.Printf("Not found.")
    case err != nil:
        log.Fatal(err)
    default:
        //do stuff
}

Otherwise, since you need to be looping over rows.Next anyways, you can easily set a flag:

defer rows.Close()
has_results := false
for rows.Next() {
    has_results = true
    //do stuff
}
if (!has_results) {
    //error handling
}