在 Golang 中,Scanner
接口(interface)采用单个 dest
参数,它是任意数量的 interface{}
:
// Scan copies the columns in the current row into the values pointed at by dest.
func (rs *Rows) Scan(dest ...interface{}) error
是否有替代函数可以返回接口(interface)片段作为其结果?假设我想将 dest
参数放在一个函数中,这样我就不必每次都写出来。
func scanArgs() []interface{} {
}
func main() {
db.QueryRow("SELECT * FROM users").Scan(scanArgs()...)
}
我已经试过了,但是我遇到了方法签名的问题;我可以将 []interface
设置为返回值,但我无法在函数内部轻松创建一个。有更好的方法吗?
最佳答案
您可以使用如下语法轻松地在函数内部进行分配;
package main
import "fmt"
func main() {
objs := &[]interface{}{}
objs2 := make([]interface{}, 10)
objs3 := []interface{}{}
fmt.Println(len(*objs))
fmt.Println(len(objs2))
fmt.Println(len(objs3))
}
由于一切都实现了空接口(interface),您可以使用 append
将任何类型添加到这些集合中。 init 语法有点笨拙,可能是什么让你感到困惑......它看起来像这样的原因是因为我在那里声明类型 interface{}
通常你会有一个名称实际界面,如[]io.Writer{}
。相反,您需要那些提取物 curl 。
关于sql - 在 Golang 中编写一个返回接口(interface) slice 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661207/