英文:
Scan database columns into struct with slices
问题
我有一个包含切片字段的结构体,现在我想将 SQL 查询的列收集到这些切片中。
type StructOfSlices struct {
Column1 []string
Column2 []string
}
有没有比下面更简单/更可扩展/更高效的方法呢?
首先,我创建一个"单个"版本的结构体...
type StructSingle struct {
Column1 string
Column2 string
}
var s StructOfSlices
rows, _ := db.Query("SELECT column1, column2 FROM table")
然后逐个扫描每个单个的结构体...
for rows.Next() {
var single StructSingle
db.Scan(&single.Column1, &single.Column2)
s.Column1 = append(s.Column1, single.Column1)
s.Column2 = append(s.Column2, single.Column2)
}
最后将其追加到切片结构体中。
英文:
I have a struct with fields containing slices like so, and now I want to collect the columns from a sql-query into these slices
type StructOfSlices struct {
Column1 []string
Column2 []string
}
Is there an easier/more scalable/efficient way to do it than the below?
Here I first create a "single" version of the struct...
type StructSingle struct {
Column1 string
Column2 string
}
var s StructOfSlices
rows, _ := db.Query("SELECT column1, column2 FROM table")
...and then scan each individual single struct...
for rows.Next() {
var single StructSingle
db.Scan(&single.Column1, &single.Column2)
s.Column1 = append(s.Column1, single.Column1)
s.Column2 = append(s.Column2, single.Column2)
}
...and then append to the slice struct
答案1
得分: 5
不,那就是正确的方法。你基本上是在进行数据透视,我不知道有什么自动完成的方法。考虑到你只用了几行代码就完成了,我认为你的解决方案没有问题。
由于你是按列扫描到一个变量中,实际上你根本不需要StructSingle
类型 - 你可以只使用两个本地的string
变量,这样会更简单:
for rows.Next() {
var col1, col2 string
db.Scan(&col1, &col2)
s.Column1 = append(s.Column1, col1)
s.Column2 = append(s.Column2, col2)
}
然后完全去掉StructSingle
类型。
英文:
No, that's the way to do it. You're basically doing a pivot, there's no way I know of to do that automagically. Given that you've done it in just a couple of lines of code, I don't see a problem with your solution.
Since you're scanning into a variable per column, you don't actually need the StructSingle
type at all - you could just use two local string
variables, which would make it even simpler:
for rows.Next() {
var col1, col2 string
db.Scan(&col1, &col2)
s.Column1 = append(s.Column1, col1)
s.Column2 = append(s.Column2, col2)
}
And get rid of the StructSingle
type entirely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论