sqlfunctiongogeneralization

Generalisation of function in Golang


I want to write a generic function which handles SQL queries.

Sqlx module provides function StructScan(), which automatically scans results into struct fields.

type Place struct {
    Country       string
    City          sql.NullString
    TelephoneCode int `db:"telcode"`
}

rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
    var p Place
    err = rows.StructScan(&p)
}

So, proposed function signature looks as:

func Query(db *sql.DB, query) {
    rows, err := db.Queryx("SELECT * FROM place")
    for rows.Next() {
        var p CustomType
        err = rows.StructScan(&p)
    }
}

The problem is that I do not know in advance the exact type of the variable denoted as Custom Type since it differs depending on a particular query (some queries returns string, another int etc).

One of the options would be to pass type CustomType as argument to Query. However, I do not know how to initialise the local variable p with needed type.

Is there a way to do it?


Solution

  • To answer your general question: That's not idiomatic Go. Instead, find a way to pass in the receiver, rather than creating it dynamically. The latter is practically impossible, and far harder to use anyway.

    To answer your specific use case, just use either sqlx's DB.Get or DB.Select, which accomplish exactly the same thing as your proposed wrapper function, but in a Go-idiomatic way.