Q:

How can I create an empty sql.Rows instance?

I have a function that returns (*sql.Rows, error) in Go. Under some circumstances, there's nothing to return, but also no error. The choices seems to be:
if (...) {
    return nil, nil
}

and then, in the caller:
rows, err := fn()
if err != nil {
    return nil, err
}

if rows == nil {
   ...
} else {
    for rows.Next() {
    ...
    }
}

or else returning a special error which I then check for. I think it would be a lot more elegant if I could return a valid Rows instance, but that does nothing but return false when its Next() method is called, like this:
if (...) {
    return EmptyRows(), nil
}

and, in the caller:
rows, err := fn()
if err != nil {
    return nil, err
}

for rows.Next() {
    ...
}

I could do something like:
if (...) {
    return db.QueryRows("select * from something where true=false"), nil
}

but that seems pretty goofy. Any recommendations?

A:

I would handle this a little differently, and just pass in the handler to your function.  So if your function is currently:
func YourFunc() (*sql.Rows, error) {
    // ...
    if (...) {
        return nil, nil
    }
    return rows, nil
}

It would have it be:
func yourFunc() (*sql.Rows, error) {
    // ...
    if (...) {
        return nil, sql.ErrNoRows
    }
    return rows, nil
}

func YourFunc(cb func(*sql.Rows)) error {
    rows, err := yourFunc()
    if err == sql.ErrNoRows {
        return nil
    }
    if err != nil {
        return err
    }
    cb(rows)
    return nil
}

And then in your caller:
err := YourFunc(func(row *sql.Rows) {
    for rows.Next() {
        // ...
    }
})

This will have the function you pass only get called if there are rows, you get the error if it's one you care about, and the caller's syntax is pretty clean.

