Write a function that returns a slice of interfaces in Golang

huangapple go评论73阅读模式
英文:

Write a function that returns a slice of interfaces in Golang

问题

在Golang中,Scanner接口接受一个名为dest的参数,该参数可以是任意数量的interface{}

// Scan将当前行中的列复制到dest指向的值中。
func (rs *Rows) Scan(dest ...interface{}) error

是否有一种替代函数可以将接口的切片作为其结果返回?比如说,我想将dest参数放在一个函数中,这样我就不必每次都写出它们。

func scanArgs() []interface{} {

}

func main() {
    db.QueryRow("SELECT * FROM users").Scan(scanArgs()...)
}

我尝试过这个方法,但是在方法签名方面遇到了问题;我可以将[]interface{}设置为返回值,但是在函数内部很难创建一个这样的切片。有没有更好的方法来实现这个?

英文:

In Golang the Scanner interface takes a single dest argument, which is any number of interface{}s:

// Scan copies the columns in the current row into the values pointed at by dest.
func (rs *Rows) Scan(dest ...interface{}) error

Is there an alternative function that can return a slice of interfaces as its result? Say I wanted to put the dest arguments in a function, so I didn't have to write them out every time.

func scanArgs() []interface{} {

}

func main() {
    db.QueryRow("SELECT * FROM users").Scan(scanArgs()...)
}

I've tried this but I'm running into issues with the method signature; I can set a []interface as the return value, but I can't easily create one inside the function. Is there a better way to do this?

答案1

得分: 1

你可以使用以下语法在函数内部轻松分配内存:

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将任何类型添加到这些集合中。初始化语法可能有点笨拙,可能会让你感到困惑...之所以看起来像那样,是因为我在那里声明了类型interface{},通常你会有一个实际接口的名称,比如[]io.Writer{}。而在这种情况下,你需要使用这些额外的花括号。

英文:

You can easily allocate inside the function with syntax like the following;

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))
}

Since everything implements the empty interface you can add any type to those collections with append. The init syntax is a bit clunky and probably what's throwing you... The reason it looks like that is because I'm declaring the type interface{} there when typically you'd have the name of an actual interface like []io.Writer{}. Instead you need those extract curlys.

huangapple
  • 本文由 发表于 2015年7月28日 03:02:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/31661207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定