How can golang sql.RawBytes be converted to variables of the actual type?

cols, err := rows.Columns() // Remember to check err afterwards
vals := make([]interface{}, len(cols))
for i, _ := range cols {
    vals[i] = new(sql.RawBytes)
}
for rows.Next() {
    err = rows.Scan(vals...)
    // Now you can check each element of vals for nil-ness,
    // and you can use type introspection and type assertions
    // to fetch the column into a typed variable.
}

official original link
the official Demo is written like this, leaving three lines of comments at the bottom:
Now you can check each element of vals for nil-ness, and you can use type introspection and type assertions to fetch the column into a typed variable.
how on earth should this use type introspection and type assertions to fetch the column into a typed variable be implemented?
looked up a lot of data but couldn"t find the answer.
most of what is said on the Internet is (string) value reversal. Maybe these statements have been going on for some years. I can"t write like this now, and I will make a mistake.

May.12,2022

answer
to connect with the official Demo. It took me a long time to get the value that can be transferred to string

.
for key, value := range vals {
    content := reflect.ValueOf(value).Interface().(*sql.RawBytes)
    row[cols[key]] = string(*content)
}

I don't know if it is necessary to do this, is there a simpler way, reflect and pointer really make me dizzy


when predicting the type of SQL return value, you can pass in the corresponding data pointer directly. Such as

    rows, err := db.Query("select id, name from foo")
    for rows.Next() {
        var id int
        var name string
        err = rows.Scan(&id, &name)
        fmt.Println(id, name)
    }

otherwise, you can query the column type and combine the reflection ( reflection ) module to operate

func (rs *Rows) ColumnTypes() ([]*ColumnType, error)

personal understanding:

    The
  • document says that you need to check whether it is nil before conversion.
  • sql.RawBytes is defined as [] byte . Normally, change to string No problem

directly defaults to the * sql.RawBytes type, which is rude.

for _, col := range vals {
    switch col.(type) {
    case *sql.RawBytes:
        rowString += string(*col.(*sql.RawBytes))
        break
Menu