[英]Convert a variable []interface{} into variable …interface{} in go
I am using a go mysql library to perform several database tasks. 我正在使用go mysql库执行一些数据库任务。 Given the fact that I want to write a wrapper package over the mysql library, I found myself into the following situation:
考虑到我想在mysql库上编写包装程序包这一事实,我发现自己处于以下情况:
I have a method with the following signature: 我有以下签名的方法:
func(db *MySQL) Insert(query string, args ...interface{}) (int64, error)
This method is calling the db.Exec
function from the library which has the following signature: 此方法从具有以下签名的库中调用
db.Exec
函数:
func (db *DB) Exec(query string, args ...interface{}) (Result, error)
It seems that when I call my method Insert("some query", 1, "test")
the values ...interface{}
is translated into []interface{}
type which is incompatible to the Exec functions argument args ...interface{}
. 似乎当我调用我的方法
Insert("some query", 1, "test")
, values ...interface{}
转换为[]interface{}
类型,与Exec函数参数args ...interface{}
不兼容args ...interface{}
。
Q1: By understanding this situation and having in consideration that I can't modify the signature of Exec
function, how would it be possible for me to transfer the args
from my Insert
function to the Exec
function? Q1:通过了解这种情况,并考虑到我不能修改
Exec
函数的签名,我怎么可能将args
从我的Insert
函数转移到Exec
函数?
I have tried several things to implement this but it seems I cannot achieve nor find a way to put my arguments in that function call. 我已经尝试了几种方法来实现此目的,但似乎无法实现也找不到找到将参数放入该函数调用的方法。
Q2: Is this even possible without modifying the signature of Exec
? 问题2:在不修改
Exec
签名的情况下,这是否有可能?
Edit: This is an example of what I am trying to achieve with the above functionality: 编辑:这是我试图通过上述功能实现的示例:
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
}
}
}
From what I understand, your problem is that when you call Exec
from Insert
with the same arguments, it considers []interface{}
as an interface{}
. 据我了解,您的问题是,当您使用相同的参数从
Insert
调用Exec
时,它会将[]interface{}
视为interface{}
。 In golang, you can expand a slice with the operator ...
. 在golang中,您可以使用运算符
...
扩展切片。 This way you can pass the arguments from Insert
to Exec
. 这样,您可以将参数从
Insert
传递给Exec
。
func exec(args ...interface{}) {
fmt.Println(args)
}
func insert(args ...interface{}) {
exec(args) // Prints [[5 42]]
exec(args...) // Prints [5 42]
}
func main() {
insert(5, "42")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.