英文:
Use Array as function call arguments
问题
在JavaScript中,你可以使用.apply
来调用一个函数并传入一个数组/切片作为函数参数。
function SomeFunc(one, two, three) {}
SomeFunc.apply(this, [1,2,3])
我想知道在Go语言中是否有相应的方法?
func SomeFunc(one, two, three int) {}
SomeFunc([]int{1, 2, 3})
Go语言的示例只是为了给你一个想法。
英文:
In JavaScript, you can use .apply
to call a function and pass in an array/slice to use as function arguments.
function SomeFunc(one, two, three) {}
SomeFunc.apply(this, [1,2,3])
I'm wondering if there's an equivalent in Go?
func SomeFunc(one, two, three int) {}
SomeFunc.apply([]int{1, 2, 3})
The Go example is just to give you an idea.
答案1
得分: 2
它们被称为可变参数函数,并使用...
语法,参见语言规范中的传递参数给...参数。
以下是一个示例:
package main
import "fmt"
func sum(nums ...int) (total int) {
for _, n := range nums { // 不关心索引
total += n
}
return
}
func main() {
many := []int{1,2,3,4,5,6,7}
fmt.Printf("Sum: %v\n", sum(1, 2, 3)) // 传递多个参数
fmt.Printf("Sum: %v\n", sum(many...)) // 参数包装在切片中
}
英文:
They are called variadic functions and use the ...
syntax, see Passing arguments to ... parameters in the language specification.
An example of it:
package main
import "fmt"
func sum(nums ...int) (total int) {
for _, n := range nums { // don't care about the index
total += n
}
return
}
func main() {
many := []int{1,2,3,4,5,6,7}
fmt.Printf("Sum: %v\n", sum(1, 2, 3)) // passing multiple arguments
fmt.Printf("Sum: %v\n", sum(many...)) // arguments wrapped in a slice
}
答案2
得分: 0
使用反射是可能的,具体来说是使用Value.Call
方法(链接),但你真的应该重新考虑为什么你想要这样做,还要了解接口的使用。
fn := reflect.ValueOf(SomeFunc)
fn.Call([]reflect.Value{reflect.ValueOf(10), reflect.ValueOf(20), reflect.ValueOf(30)})
英文:
It is possible using reflection, specifically Value.Call
, however you really should rethink why you want to do that, also look into interfaces.
fn := reflect.ValueOf(SomeFunc)
fn.Call([]reflect.Value{reflect.ValueOf(10), reflect.ValueOf(20), reflect.ValueOf(30)})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论