duanhuayong6687 2018-12-07 07:46
浏览 246
已采纳

如何传递* interface {}的一部分作为参数?

I want to use Scan() in package sql, but the number of columns, and hence the number of arguments, will change at runtime. This is the signature of Scan():

func (rs *Rows) Scan(dest ...interface{}) error

According to the documentation, *interface{} is one of the types accepted by Scan(). So I want to create a slice of []*interface{} and that expand as arguments.

This is what I thought would work:

func query(database *sql.DB) {
    rows, _ := database.Query("select * from testTable")

    for rows.Next() {
        data := make([]*interface{}, 2)
        err := rows.Scan(data...) // Compilation error
        fmt.Printf("%v%v
", *data[0], *data[1])
        if err != nil {
            fmt.Println(err.Error())
        }
    }
}

Compilation fails with cannot use data (type []*interface {}) as type []interface {} in argument to rows.Scan. I thought that data... would expand to &data[0], &data[1], but apparently not. I don't understand the error message. *interface{} is compatible with interface{}, so why can't I expand the slice of pointers to interface types?

This works:

func query(database *sql.DB) {
    rows, _ := database.Query("select * from testTable")

    for rows.Next() {
        data := make([]*interface{}, 2)
        err := rows.Scan(&data[0], &data[1]) // Only changed this line
        fmt.Printf("%v%v
", *data[0], *data[1]) // Outputs "[48][116 101 120 116]"
        if err != nil {
            fmt.Println(err.Error())
        }
    }
}

I can't use this however, because the number of columns is unknown at compile time. How can I write this code so that I can pass a variable number of *interface{} to rows.Scan()?

  • 写回答

1条回答 默认 最新

  • douxiong5972 2018-12-07 07:53
    关注

    First, you must not use []*interface{} slice of pointers to interface rather than []interface{} where the interfaces are pointers. []*interface{} is different from []interface{}. Just create a slice of interfaces where each element is a pointer to a concrete type.

    Here is a snippet how you would do this.

    var x int
    var s string
    
    data := []interface{}{&x, &s}
    
    rows.Scan(data...)
    

    Note on the use of the ... spread operator.

    Here are some related questions that will explain a bit more:

    golang: slice of struct != slice of interface it implements?

    Cannot convert []string to []interface {}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名