dongyipa0028 2012-12-11 02:12
浏览 68
已采纳

如何将结构指针转换为go中的类型指针列表

I have a struct that looks like:

type inv struct {
    ID   int     `json:"id"`
    Name string  `json:"name"`
}

I'm querying some data from the database(assuming there are no errors):

rows, err := db.Query("select id, name from inv_table")

Normally, I'd have to pull the data from the row by scanning

var i inv
for rows.Next() {
    rows.Scan(&i.ID, &i.Name)
}

I think this might work (to be tested tomorrow):

var i inv
for rows.Next() {
    var x []interface{} = [&i.ID, &i.Name]
    rows.Scan(x... )
}

In actuality I have many more columns in the result set from the query.

rows.Scan(&i)

or at least:

rows.Scan(getExportedValuePointers(&i)... )

I suppose I could always write some sort of encoder, however, it seems to me that there should be something in the box already.

** I realize that I could always write some reflection code similar to the encode/xml or encode/json ... but I'm hoping that someone has already done it.

UPDATE: The following code works as expected but not as I want:

package main
import "fmt"
type inv struct {
    A int
    B string
}
func main() {
    var i inv
    fmt.Printf("hello
")
    n, err := fmt.Sscan("1 c", &i.A, &i.B)
    fmt.Printf("retval: %d %#v
", n, err)
    fmt.Printf("retval: %d, %s, %d %#v
", i.A, i.B, n, err)
    j := []interface{}{&i.A, &i.B}
    k := []interface{}{i.A, i.B}
    n, err = fmt.Sscan("2 d", j... )
    fmt.Printf("retval: %d, %s, %d %#v
", i.A, i.B, n, err)
    fmt.Printf("retval: %d, %s
", k... )
}
  • 写回答

2条回答 默认 最新

  • doulan9287 2012-12-13 03:57
    关注

    If you're looking for a package that will automatically bind your SQL query to your "inv" struct then take a look at gorp:

    https://github.com/coopernurse/gorp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算