Home > Mobile >  How to pass values to a variadic parameter in a func from a variadic arguement
How to pass values to a variadic parameter in a func from a variadic arguement

Time:01-21

The sql library func QueryContext takes variadic parameter for the where clause. I would like to create a helper function that takes variadic parameter and send that to QueryContext call. Here is my code snippet:

func GenericDBSelect(ctx context.Context, qry string, params ...string) (*sql.Rows, error) {

//format the connectstr db, err := sql.Open("mysql", connectstr)

if err != nil || db == nil {
    msg := "could not get db connection. Is DB available?"
    return nil, fmt.Errorf(msg)
}

rows, err := db.QueryContext(ctx, qry, params)

if err != nil {
    msg := fmt.Sprintf("Could not prep query = %v, params = %v. Error = %v ", qry, params, err)
    
    return nil, fmt.Errorf(msg)
}

return rows, err

}

And I call

rows, err := GenericDBSelect(ctx, qry, param1, param2)

When I run this code, it throws the following error:

sql: converting argument $1 type: unsupported type []string, a slice of string 

The problem seems to be that the params in GenericDBSelect is received as []string instead of ...string.

CodePudding user response:

Make these two changes:

  • Declare GenericDBSelect to take the same type of variadic argument as QueryContext. This allows params to be passed through with no conversion.

      func GenericDBSelect(ctx context.Context, 
           qry string, params ...any) (*sql.Rows, error) {
    
  • Pass the variadic arguments to QueryContext using the ... syntax:

     rows, err := db.QueryContext(ctx, qry, params...)
    

See Passing arguments to ... parameters for more information.

  •  Tags:  
  • go
  • Related