Extend golang struct
Starting with Go Templates, what does the T indicate in {{T "post_nav_prev"}}
How do I run shell command in golang
How to implement a retry mechanism for goroutines?
Use package file to write to Cloud Storage?
How to copy a non-pointer value to a pointer indirected value via reflection
GO array expansion
Go server empty response in Docker container
Go app runs fine locally, produces 404 when running goapp serve
how to get free ip in range 127.0.0.1 - 127.0.x.255 with golang?
Change dataType from bigquery.Value to string
How to change the date/time format of Go's log package
Volume mount option 'z' using docker golang library
Golang: Interrupting infinite polling having time.Sleep
Can't deploy go lang app to AWS Elastic Beanstalk
Run Vec of futures concurrently but with only n at a time
Rust Rocket with SQLX test database endpoints
Why these errors are not automagically converted to my custom error even if they are implementing both std::error::Error trait?
Wio Terminal how to use `writeln` method in UART
The ability to compile a rust program using python
Slow Rust Performance for a SSH Log Parsing project
Deserialize hcl with labels
rust nalgebra set a block in matrix to rotation?
Using crates installed from Debian repositories in my Rust app
How to achieve single threaded concurrency with blocking functions in Rust?
How to print the output of seaching a string from a no of files to a output File In Perl
Extract number from array in Perl
Data Extraction & Pattern Matching
Perl trim path regex
file compare in perl
grep foldername and sub file content
Regarding regular expression in Perl
Setenv $PATH not functioning properly
how to replace , to . in large text file
Perl: How to perfectly match specific data between two files and do comparison?
A more generalizable solution is to use the
sqlx
library:
https://jmoiron.github.io/sqlx/#inQueries
// assume db is an initialized database handle
somevars := []int{1,2,3,4}
query, args, err := sqlx.In("SELECT * FROM table WHERE id IN (?)", somevars)
if err != nil {
return err
query = db.Rebind(query)
result := db.Select(query, args...)
This solution will work with multiple database drivers and slices of unknown length.
somevars := []interface{}{1, 2, 3, 4}
rows, err = db.Query(
"SELECT c1,c2 FROM table"+tid+" WHERE c1 IN($1,$2,$3,$4);",
somevars...)
Here the ...
expands a slice to multiple arguments, similar to the python *args
. It's documented in the language spec.
The db.Query
API supports this so called variadic parameter.
func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
Here interface{}
is known as the empty interface, and it can hold values of any type. See the Go tour example here. So one can use it like
db.Query(stmt, var1, var2)
where var1
var2
could be of different types.
In your case, you can also pass the slice elements explicitly
db.Query(stmt,
somevars[0], somevars[1], somevars[2], somevars[3])
But it is rather verbose and requires extra work when the slice length changes.
Note that if instead of the interface
slice somevars
, we use intvars := []int {1, 2, 3, 4}
and expand intvars
in db.Query()
, the compiler will complain on intvars...
cannot use []int literal (type []int) as type []interface {} in assignment
Type conversion intvars.([]interface{})
doesn't work either. This is documented in the language spec FAQ. And there is also a dedicated wiki page for it
It is disallowed by the language specification because the two types do not have the same representation in memory.
The intuitive picture of golang interface
is an object with two fields, one field stores a type, and the other stores a pointer.
sql: converting argument $1 type: unsupported type []int, a slice of in
golang - Save enum type to SQL database "panic: sql: converting Exec argument #1's type: non-Value type int returned from Value"
sql: converting argument $1 type: unsupported type []uuid.UUID, a slice of array
Converting argument $1 type: unsupported type []interface {}, a slice of interface
Why am I getting a compile error 'cannot use ... as type uint8 in argument to ...' when the parameter is an int
Converting Slice of custom type to slice of string
Slice inside struct, cannot use type int64 as int in slice literal
In golang, how to return a slice of type int from a function to another function?
Fast way of converting a slice of type T, to a slice of byte in Go
Golang Error : Cannot use (type [5]int) as type int in argument to median
Converting map keys of type array to a 2D slice
Filling a slice of interface type given as argument (e.g., implement a ScanAll for database/sql)
Allow a slice of any type into as argument
Err: cannot use c.Param("id") (type string) as type int in argument to services.GetCharactersID
What's the language rule behind converting a string type to byte slice and what's actually being done in this conversion?
Type converting slices of interfaces
The maximum value for an int type in Go
How to prepend int to slice
unsupported Scan, storing driver.Value type []uint8 into type *time.Time
Converting a custom type to string in Go
Is there a built in min function for a slice of int arguments or a variable number of int arguments in golang?
Parse string to specific type of int (int8, int16, int32, int64)
How to pass type to function argument in Go
What is the point of slice type in Go?
Scan error: unsupported Scan, storing driver.Value type <nil> into type *string
Can I type assert a slice of interface values?
Initialize custom int type in Go
How to remove duplicates strings or int from Slice in Go
Go: cast any int value to int64 in type switch
Conversion of a slice of string into a slice of custom type
Exporting functions with anonymous struct as a parameter [cannot use value (type struct {...}) as type struct {...} in argument to package.Func]
How can I instantiate a non-nil pointer of type argument with generic Go?
Golang: get the type of slice
GoLang conventions - create custom type from slice
Accept function in argument with empty interface return type
Why does type int exist in Go
Slicing a slice pointer passed as argument
Golang CGo: converting union field to Go type
unsupported Scan, storing driver.Value type []uint8 into type *[]string
How to use Go reflection pkg to get the type of a slice struct field?
How to determine the element type of slice interface{}?
More idiomatic way in Go to encode a []byte slice int an int64?
Read space separated integers from stdin into int slice
Initialize golang slice with int numbers from 0 to N
Performance: Sorting Slice vs Sorting Type (of Slice) with Sort implementation
Converting int and long into string in Go
Why does golang allow named slice type assignment without explicit type conversion?
Creating Slice from Reflected Type
First argument to append must be slice
Golang converting float64 to int error
More Query from same tag
When debugging, GoLand can not evaluate a function on M1
Simpler way to type assert a two-dimensional interface array from json unmarshal
How to write a GET endpoint in Gin that lets the user download a file + metadata in json format?
panic: testing: Verbose called before Init
Using slices and Arrays in go error
Stringer can't generate constants with values from C enum
How can I import a library from github to GO playground?
Regex to find repetive number of length n
Cgo linker errors on C constants
package with objects that need cleanup
Sequence alignment of multiple slices of ints in golang
unexpected sync.Pool allocation
Configuring OTLP exporter through environment variables
go Unable to get login user information
Serial execution of package tests
Print spooler concept / API & Channels: issue passing jobs to a queue from serveHTTP
How to check if kubernetes job is successful or failure using client go library
Proper way to SQL select and update
Unmarshal embedded field pointer panics when field implements UnmarshalJSON
How do segmented stacks work
Can I unmarshal JSON into implementers of an Interface?
How to add multiple test reports to SonarQube
How does my GAE local server connect to firebase emulator
Kubernetes client-go: watch.Interface vs. cache.NewInformer vs. cache.NewSharedIndexInformer?
Attach shipping information to Stripe Charge using Go
Is there a way to get the Type for a Column using package database/sql in golang?
Typing in recursive golang function call
implement github.com/jlaffaye/ftp in golang
One HTTP Delimiter to Rule Them All
Go does not kill GUI based processes even after setting the process group pid
How to constrain Go's grpc go routine number
What's the closure scoping difference between short variable declarations and long ones in Go?
Go equivalent to std::set?
How to check for goroutine completion while actively reading from channel?
How do I create static dates in golang?
Which database fits better this model: I have a JSON tree, users can add comments for any key
Why did Happybase's connection to Hbase Thrift just stop working?
Read from a realtime API and store all messages
Prevent dynamodb scans by saving sorted and filtered record ids in the database
Google Datastore Querying Set
Best practice for displaying Firebase many-to-many relationships in the view (AngularFire)