LoginSignup
8
5

More than 5 years have passed since last update.

structではなくinterfaceにScanした値を入れる

Last updated at Posted at 2016-08-28

GormsqlxのようなGolangのデータベースライブラリではプリミティブな機能である(*DB) Rows(*Rows) Scanが使用できる。
(*Rows) Scanの引数は大抵の場合structで紹介されているがinterface{}にScanした値をいれることができる。

以下がスニペット。


rows, err := sql.Rows()

var results []map[string]interface{}
cols, err := rows.Columns()

for rows.Next() {
    var row = make([]interface{}, len(cols))
    var rowp = make([]interface{}, len(cols))
    for i := 0; i < len(cols); i++ {
        rowp[i] = &row[i]
    }

    rows.Scan(rowp...)

    rowMap := make(map[string]interface{})
    for i, col := range cols {
        switch row[i].(type) {
        case []byte:
            row[i] = string(row[i].([]byte))
            num, err := strconv.Atoi(row[i].(string))
            if err == nil {
                row[i] = num
            }
        }
        rowMap[col] = row[i]
    }

    results = append(results, rowMap)
}

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5