dpj775835868 2019-09-05 16:42
浏览 559
已采纳

args…interface {}对于方法的参数究竟意味着什么? [重复]

This question already has an answer here:

I am referring to following method that takes last argument as args ...interfact{})

func (*sqlx.DB).Select(dest interface{}, query string, args ...interface{}) error

https://godoc.org/github.com/jmoiron/sqlx#DB.Select

From my understanding that the method accepts last parameter of any type which is variadic ..

So

    selectStmt = 'Select * FROM users where user_id IN (?)'
    selectStmt, userArgs, err := sqlx.In(selectStmt, userIDs)// userIDs is a slice
    if err != nil {
        return nil, errors.Wrap(err, "")
    }

    selectStmt = s.db.Rebind(selectStmt)


    var users []User
        err = s.db.Select(&users, selectStmt, userArgs) // wrong one .. Line A

    err = s.db.Select(&users, selectStmt, userArgs... ) // right one .. Line B


In the aforementioned code if i comment out Line B , but not Line A it doesn't work. I get following error.

  • sql: converting argument $1 type: unsupported type []interface {}, a slice of interface *

Question

What exactly happening here , why can't go infer the variadic automatically ?? What is the need of passing extra '...' to the third argument?

</div>
  • 写回答

1条回答 默认 最新

  • duanpan7011 2019-09-05 16:44
    关注

    What exactly happening here , why can't go infer the variadic automatically ?? What is the need of passing extra '...' to the third argument?

    Go doesn't infer the variadic automatically - in fact, Go intentionally infers very little and does very little automatically. You need the ... because it does not infer. It also makes clear, when you pass a slice to a variadic, whether you mean for it to be exploded, or you mean for the slice itself to be a single argument; either could be a valid use case, and rather than making assumptions, Go expects you to be explicit.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)