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

报告相同问题?

悬赏问题

  • ¥50 STM32L431RCT6 定时器2中断发起ADC 采样问题
  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker