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

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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题