英文:
Golang equivalent of JavaScript's arguments?
问题
有没有一种在golang中获取函数运行时参数的方法?
我问这个问题是因为我正在尝试编写一个函数,该函数接受一个函数和一个字符串作为参数,然后输出该字符串和函数的运行时参数。
英文:
Is there a golang way to get a function's runtime arguments?
I'm asking because I'm trying to write a function that takes a function and a string, and then outputs the string and the runtime arguments.
答案1
得分: 3
与JavaScript不同,Go语言中的函数调用必须与函数签名匹配,不能传递未在声明中包含的额外参数,因此不需要特殊的arguments全局变量。
尽管如此,我们仍然可以编写可变参数函数,以接受可变数量的参数。例如,下面的函数将接受一个字符串参数,后面可以跟任意数量的整数参数:
func foo(s string, args ...int) {
    // 函数体
}
在函数体中,args将是一个[]int切片,因此你可以使用len确定传递了多少个参数,并像处理其他切片一样进行迭代。
如果你想接受任意类型的参数,可以使用空接口作为类型:
func bar(args ...interface{}) {
    // 函数体
}
现在,args将是一个[]interface{}切片。你可以使用类型断言或类型切换来提取传入的值。
英文:
Unlike JavaScript where a function can be called with extra arguments not included in the declaration, calls to Go functions must match the function signature.  So there isn't a need for the special arguments global.
With that said, it is possible to write variadic functions that can take a variable number of arguments. For example, the following function will accept a string followed by any number of integer arguments:
func foo(s string, args ...int) {
    ...
}
In the function body args will be an []int slice, so you can determine how many arguments were passed with len, and iterate through them as you would with any other slice.
If you want to accept arguments of any type, you can use the blank interface as the type:
func bar(args ...interface{}) {
    ...
}
Now args will be an []interface{} slice.  You can unpack the values passed in using a type assertion or type switch.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论