我有一个结构:
type mystruct struct {
Foo string
Bar int
}
我想从具有以下形式的结构创建 SQL 插入语句:
m := mystruct{ "Hello" , 1 }
query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
res,err := db.Exec(query, m.Foo, m.Bar)
现在我的问题是:如何从结构(或 m)本身动态地制作最后一行?我可以使用 获取结构名称reflect
,但我不知道如何为调用创建[]interface{}
切片。db.Exec()
这是我尝试过的:(http://play.golang.org/p/GR1Bb61NFH)
package main
import (
"fmt"
"reflect"
)
type mystruct struct {
Foo string
Bar int
}
func main() {
m := mystruct{"Foo", 1}
fmt.Println(readNames(m))
x := unpackStruct(m)
fmt.Printf("%#v\n", x)
}
func unpackStruct(a interface{}) []interface{} {
// "convert" a to m t
// doesn't work, from 'laws of reflection'
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
// this is in principle what I want:
m := mystruct{"Hello", 2}
var ret []interface{}
ret = make([]interface{}, s.NumField())
ret[0] = m.Foo
ret[1] = m.Bar
return ret
}
// works fine:
func readNames(a interface{}) []string {
s := reflect.TypeOf(a)
lenStruct := s.NumField()
ret := make([]string, lenStruct)
for i := 0; i < lenStruct; i++ {
ret[i] = s.Field(i).Name
}
return ret
}