英文:
how to convert a struct pointer to list of type pointers in go
问题
我有一个类似的结构体:
type inv struct {
ID int `json:"id"`
Name string `json:"name"`
}
我正在从数据库查询一些数据(假设没有错误):
rows, err := db.Query("select id, name from inv_table")
通常情况下,我需要通过扫描来从行中提取数据:
var i inv
for rows.Next() {
rows.Scan(&i.ID, &i.Name)
}
我认为这可能会起作用(明天要测试一下):
var i inv
for rows.Next() {
var x []interface{} = []interface{}{&i.ID, &i.Name}
rows.Scan(x...)
}
实际上,查询结果集中还有更多的列。
rows.Scan(&i)
或者至少:
rows.Scan(getExportedValuePointers(&i)...)
我想我可以编写一些类似于encode/xml或encode/json的反射代码,但我希望有人已经做过了。
更新:以下代码按预期工作,但不是我想要的:
package main
import "fmt"
type inv struct {
A int
B string
}
func main() {
var i inv
fmt.Printf("hello\n")
n, err := fmt.Sscan("1 c", &i.A, &i.B)
fmt.Printf("retval: %d %#v\n", n, err)
fmt.Printf("retval: %d, %s, %d %#v\n", 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\n", i.A, i.B, n, err)
fmt.Printf("retval: %d, %s\n", k... )
}
英文:
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")
n, err := fmt.Sscan("1 c", &i.A, &i.B)
fmt.Printf("retval: %d %#v\n", n, err)
fmt.Printf("retval: %d, %s, %d %#v\n", 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\n", i.A, i.B, n, err)
fmt.Printf("retval: %d, %s\n", k... )
}
答案1
得分: 2
如果你正在寻找一个可以自动将你的SQL查询绑定到你的"inv"结构体的包,那么可以看一下gorp:
https://github.com/coopernurse/gorp
英文:
If you're looking for a package that will automatically bind your SQL query to your "inv" struct then take a look at gorp:
答案2
得分: 0
没有自动完成这个任务的方法,但是你可以使用反射包(reflect package)编写一个函数来实现。
英文:
There is nothing to do this automatically, but you could write a function using the reflect package to do it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论