[英]Write a function that returns a slice of interfaces in Golang
在Golang中, Scanner
接口使用單個dest
參數,該參數可以是任意數量的interface{}
:
// Scan copies the columns in the current row into the values pointed at by dest.
func (rs *Rows) Scan(dest ...interface{}) error
是否有一個替代函數可以返回一部分接口作為其結果? 假設我想將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))
}
由於所有內容都實現了空接口,因此您可以使用append
將任何類型添加到這些集合中。 init語法有點笨拙,可能會把您扔掉……看起來像這樣的原因是因為當您通常使用實際的接口名稱,例如[]io.Writer{}
時,我在那里聲明了type interface{}
[]io.Writer{}
。 相反,您需要那些提取的卷發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.