Home > Backend Development > Golang > How Can I Efficiently Use Go Reflection to Call the `Scan` Variadic Function with a Dynamic Number of Pointers?

How Can I Efficiently Use Go Reflection to Call the `Scan` Variadic Function with a Dynamic Number of Pointers?

Susan Sarandon
Release: 2024-12-10 00:21:14
Original
852 people have browsed it

How Can I Efficiently Use Go Reflection to Call the `Scan` Variadic Function with a Dynamic Number of Pointers?

Calling Scan Variadic Function with Reflection in Go

The Scan() method of Row interface in the database/sql package allows efficient retrieval of values from a database row by passing a variadic list of pointers to values of correct type. While useful, working with this method using reflection to obtain values from a variable number of pointers can be challenging.

Solution

The provided solution overcomes this challenge by dynamically creating two slices: one for storing values and one for holding parallel pointers. Using pointers to collect data in the values slice enables the population of other data structures.

Code

package main

import (
    "fmt"
    _ "github.com/lib/pq"
    "database/sql"
)

func main() {
    db, _ := sql.Open(
        "postgres",
        "user=postgres dbname=go_testing password=pass sslmode=disable")

    rows, _ := db.Query("SELECT * FROM _user;")

    columns, _ := rows.Columns()
    count := len(columns)
    values := make([]interface{}, count)
    valuePtrs := make([]interface{}, count)

    for rows.Next() {
        for i := range columns {
            valuePtrs[i] = &values[i]
        }

        rows.Scan(valuePtrs...)

        for i, col := range columns {
            val := values[i]

            b, ok := val.([]byte)
            var v interface{}
            if (ok) {
                v = string(b)
            } else {
                v = val
            }

            fmt.Println(col, v)
        }
    }
}
Copy after login

The code first opens a connection to the database and executes a query. It then determines the number of columns in the result set and creates two slices, values and valuePtrs, with the same length as the columns.

Inside the loop over the rows, the valuePtrs slice is populated with the addresses of each element in the values slice. The rows.Scan() method is then called with the valuePtrs slice, effectively populating the values slice with the data from the current row.

Finally, the code iterates over the column names and values, converting byte slices to strings if necessary, and printing the results.

The above is the detailed content of How Can I Efficiently Use Go Reflection to Call the `Scan` Variadic Function with a Dynamic Number of Pointers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template