使用数组作为函数调用的参数

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

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...)) // 参数包装在切片中
}

Playground 示例

英文:

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
}

Playground example

答案2

得分: 0

使用反射是可能的,具体来说是使用Value.Call方法(链接),但你真的应该重新考虑为什么你想要这样做,还要了解接口的使用。

fn := reflect.ValueOf(SomeFunc)
fn.Call([]reflect.Value{reflect.ValueOf(10), reflect.ValueOf(20), reflect.ValueOf(30)})

playground

英文:

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

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年9月14日 06:31:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/25828358.html
匿名

发表评论

匿名网友

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

确定