在 Go 中,我试图将 一个 传递给 函数从 .我确信这是一个已解决的问题,但我无法弄清楚。interface{}statement.Exec()go-sqlite3基本上,我有一个行数据,我想将其传递给一个函数,该函数将它插入到sqlite db中。问题是我希望能够以编程方式控制函数中的内容structstatement.Exec()以下是摘录:type hostRows struct { domain string}type clientRows struct { name string}func main() { ... data := hostRows{domain: "dom.com"} insertRow(sqliteDatabase, data) data2 := clientRows{name: "bob"} insertRow(sqliteDatabase, data2) ...}func insertRow(db *sql.DB, row interface{}) { insertSQL := "INSERT INTO table(col) VALUES (?)" statement, _ := db.Prepare(insertSQL) statement.Exec(row) // here's the issue, how can I extract the element in the interface to pass it to the function for Exec to understand }我知道在此示例中,我可以将行类型硬编码为结构和类型,但现在代码将中断到传递客户端结构时。statement.Exec(row.(hostRows).domain)这是函数的减速Execfunc (s *Stmt) Exec(args ...interface{}) (Result, error) 我尝试过玩,但到目前为止它还没有对我有用。我目前唯一的解决方案是使用一个条件,可以检查并准备正确的命令,但这还不够狡猾。reflectswitchExectype hostRows struct { domain string}type clientRows struct { name string}func main() { ... data := hostRows{domain: "dom.com"} insertRow(sqliteDatabase, 1, data) data2 := clientRows{name: "bob"} insertRow(sqliteDatabase, 2, data2) ...}func insertRow(db *sql.DB, i int, row interface{}) { insertSQL := "INSERT INTO table(col) VALUES (?)" statement, _ := db.Prepare(insertSQL) // This basically could be a working solution, but I'm sure there is a better one switch i { case 1: data := row.(hostRows) statement.Exec(data.domain) case 2: data := row.(clientRows) statement.Exec(data.name) } }编辑:更正了 INSERT 语句 ;忘记列。更正为 edit2:添加了第二个示例statement.Exec(row.domain)statement.Exec(row.(hostRows).domain)
1 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
请记住,为了工作,您必须导出字段。要使用反射实现所需的效果,可以尝试如下操作:reflect.Interface()
type hostRows struct {
//Should export field to read it using reflect.Value.Interface()
Domain string
}
type clientRows struct {
//Should export field to read it using reflect.Value.Interface()
Name string
}
func insertRow(db *sql.DB, i int, row interface{}) {
rv := reflect.ValueOf(row)
var args []interface{}
for i := 0; i < rv.NumField(); i++ {
args = append(args, rv.Field(i).Interface())
}
db.Exec("Insert Satement...", args...)
}
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报
0/150
提交
取消