doudundian9558 2014-09-13 22:31
浏览 67
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • douyinmian8151 2014-09-14 15:09
    关注

    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
    ", sum(1, 2, 3)) // passing multiple arguments
        fmt.Printf("Sum: %v
    ", sum(many...)) // arguments wrapped in a slice
    }
    

    Playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!