【问题标题】:Convert a variable []interface{} into variable ...interface{} in go在 go 中将变量 []interface{} 转换为变量 ...interface{}
【发布时间】: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


【解决方案1】:

据我了解,您的问题是,当您使用相同的参数从Insert 调用Exec 时,它会将[]interface{} 视为interface{}。在 golang 中,您可以使用运算符 ... 扩展切片。这样您就可以将参数从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")
}

【讨论】:

  • 你是救生员!确实。我忘记了我可以扩展参数列表的事情!非常感谢!!!!
猜你喜欢
  • 2016-05-21
  • 2020-03-03
  • 1970-01-01
  • 2020-07-17
  • 2017-01-01
  • 2018-11-10
  • 2015-01-14
  • 2014-02-22
  • 2014-09-16
相关资源
最近更新 更多