I want to pass Go's slice to a function that accepts variable length arguments by reference.
It looks like the following code.
package main
func f (i ... interface {}) {
// pass to this function by reference
}
func main () {
s: = make ([] interface {}, 10)
f ((&s) ...) // error here
}
However, this code results in the following error:
cannot use&s (type * [] interface {}) as type [] interface {} in argument to f
Tell me if you have a way to pass Go's slice to a function that accepts variable length arguments.
Although it is necessary to do the above in the process of creating an ORM in the Go language, it would be helpful if you could tell me if there is an alternative.
Specifically, I am trying to do something like the following code.
// db is database/sql.DB
rows, _ = db.Query ("Query")
for rows.Next () {
numFields: = 10 // actually get the number of fields in the structure (10 is an example)
datas: = make ([] interface {}, len (numFields))
rows.Scan (datas ...) // Cannot get value because it cannot be passed by reference
}
I am in trouble because I can't pass by reference where I commented that "I can't get a value because I can't pass by reference" in this code.
If i have any alternatives to achieve this, other than passing slice to a function that accepts variable-length arguments, it would be helpful.
-
Answer # 1
Related articles
- how to use a colon in a go slice
- go - i want to pass randoseed to another function
- go - how to combine and output the output of function and fmtprintln
- python - why does the slice [start:stop] of the pandas function loc include stop?
- pointer in a golang function
- go - i want to store standard input in a slice
- go - how to use function return
- (go language) i want to call a function from another package in go
- go slice operation
- go - slice element deletion syntax
- i don't know the slice of a tour of go
- i want to define a slice in golang template
- Exploring the In Function of a Slice in Go
Title and answer as Go specification
Slice is originally a reference type, so if you change the value by passing a slice to a normal function argument, it will be reflected in the source.
How to use rows.ScanHowever, if a variable-length argument is passed as both slices, the result will be like passing by reference.
https://play.golang.org/p/xpf1muwMat-
Each argument of rows.Scan must be a reference type,
There is no notion of interface type reference type in Go.
It's a little on the go so it's almost over writing. I will add it later.