duanjuda5789 2018-02-18 07:40
浏览 82

去变参函数参数传递

I am trying to understand, What is difference between 1st and 2nd passing argument in function. In both case methods are functional and compiles.

1)

generateReport(capacities...)

func generateReport(capacities ...float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f
", i, cap)
    }
}

2)

generateReport(plantCapacities)

func generateReport(capacities []float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f
", i, cap)
    }
}

Have found few good samples

1) GolangBot - Variadic Function

2) Golang.org - Passing arguments as @Himanshu mentioned.

  • 写回答

1条回答 默认 最新

  • douguan1887 2018-02-18 08:03
    关注

    According to Golang language specification

    If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

    variadic functions are used to handle multiple trailing arguments. It can be used to pass slice arguments.

    func main(){
      capacities := []float64{1, 2, 3, 4}
      generateReport(capacities...)
    }
    
    func generateReport(capacities ...float64) {
        for i, cap := range capacities {
            fmt.Printf("Plant %d capacity %.0f
    ", i, cap)
        }
    }
    

    Variadic functions can also be called in usual way with individual arguments. It works like spread operator in java script which can take multiple arguments. For eg:-

    func main(){
      generateReport(1,2,3,4)
    }
    
    func generateReport(capacities ...float64) {
        for i, cap := range capacities {
            fmt.Printf("Plant %d capacity %.0f
    ", i, cap)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看