参数作为具有可变数量参数的函数

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

Arguments as functions with variable number of arguments

问题

如何在Golang中传递一个函数作为参数,该函数可以具有潜在的多个参数,例如fmt.Printf

第一个问题是必须首先定义要传递的函数的类型。

type FunctionWithVariableArgumentLength func(s string, object1 type1, ..., objectn typen)

第二个问题是不知道列表中的参数可能具有什么类型,就像在fmt.Printf中一样。

英文:

How can I pass in Golang a function as an argument that can have potentially multiple arguments, e.g. fmt.Printf?

The first problem is that one has to define the type of the function to be passed first.

type FunctionWithVariableArgumentLength func(s string, object1 type1, ..., objectn typen)

The second problem is that one does not know what types the arguments in the list may have, like in fmt.Printf.

答案1

得分: 4

这里有一个关于其他函数的原型:http://golang.org/pkg/fmt/#Printf

所以你可以像这样定义一个接受函数作为参数的函数:

func exe(f func(string, ...interface{}) (int, error)) {
    f("test %d", 23)
}
func main() {
    exe(fmt.Printf)
}

演示

英文:

There's a prototype as for other functions : http://golang.org/pkg/fmt/#Printf

So you can define your function accepting a function as argument like this :

func exe(f func(string, ...interface{}) (int, error)) {
    f("test %d", 23)
}
func main() {
	exe(fmt.Printf)
}

Demonstration

答案2

得分: 2

你可以使用与fmt.Printf相似的签名:

func yourFunction(a ...interface{})
英文:

You would use a similar signature as the one for fmt.Printf

func yourFunction(a ...interface{})

答案3

得分: 2

回答第一部分:编写具有可变数量参数的函数。

// sums 函数返回可变数量参数的总和
func sum(numbers ...int) total int {
    total = 0
    for _, n := range numbers {
        total += n
    }
    return total
}

第二部分比较困难,但函数定义如下:

func doVarArgs(fmt string, a ...interface{}) {

变量 a 包含了类型为 interface{} 的值的切片。然后你可以遍历该切片,提取每个参数,并使用包 "reflect" 查询每个参数的类型。

详细说明请参考 http://golang.org/pkg/reflect/

英文:

To answer the 1st part: writing functions with a variable number of arguments.

// sums returns the total of a variable number of arguments
func sum(numbers ...int) total int {
    total = 0
    for _, n := range numbers {
        total += n
    }
    return total
}

The 2nd Part is harder but the function definition looks like:

func doVarArgs(fmt string, a ...interface{}) {

The variable a contains a slice of values of the type interface{}. You then iterate over the slice pulling each argument and using the package "reflect" to query the type of each argument.

See http://golang.org/pkg/reflect/ for a full explanation.

huangapple
  • 本文由 发表于 2014年9月10日 20:35:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/25765640.html
匿名

发表评论

匿名网友

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

确定