【发布时间】:2016-09-18 15:44:34
【问题描述】:
我正在使用 go mysql 库来执行几个数据库任务。鉴于我想在 mysql 库上编写一个包装器包,我发现自己陷入了以下情况:
我有一个带有以下签名的方法:
func(db *MySQL) Insert(query string, args ...interface{}) (int64, error)
此方法正在调用库中的db.Exec 函数,该函数具有以下签名:
func (db *DB) Exec(query string, args ...interface{}) (Result, error)
似乎当我调用我的方法 Insert("some query", 1, "test") 时,values ...interface{} 被转换为与 Exec 函数参数 args ...interface{} 不兼容的 []interface{} 类型。
Q1:通过了解这种情况并考虑到我无法修改Exec函数的签名,我怎么可能从我的@转移args 987654330@函数改成Exec函数?
我已经尝试了几件事来实现这一点,但似乎我无法实现,也找不到将我的参数放入该函数调用的方法。
Q2:即使不修改Exec的签名,这也可能吗?
编辑:这是我试图通过上述功能实现的一个示例:
func(db *MySQL) Insert(query string, values ...interface{}) (int64, error) {
/**
* TODO: find a way to implement the args slice
* to implement this remember that behind Exec(_, values) there is a [] interface{} element
* which will decompose this element inside. so by passing a values ...interface{} function won't work
* as the values ...interface{} has another data type structure in the end
*/
//
if res, err := db.dbConn.Exec(query, values); err != nil {
return -1, err
} else {
if lastId, err := res.LastInsertId(); err != nil {
return -1, err
} else {
return lastId, nil
}
}
}
【问题讨论】:
-
为什么不像GORM那样使用ORM呢?它更容易
-
我还是 Go 语言的初学者。所以我试图找出这种编程语言的大部分好处和心态。 GORM 似乎实际上是我正在寻找的解决方案,所以我会检查它。非常感谢您的回复!
标签: function go types type-conversion