Go可变函数参数传递

标签 go

我想了解,函数中第一个和第二个传递参数之间有什么区别。在这两种情况下,方法都是功能性的并且可以编译。

1)

generateReport(capacities...)

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

2)

generateReport(plantCapacities)

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

已经找到几个好的样本

1) GolangBot - Variadic Function

2) Golang.org - Passing arguments正如@Himanshu 提到的。

最佳答案

根据 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 函数用于处理多个尾随参数。它可用于传递 slice 参数。

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\n", i, cap)
    }
}

可变参数函数也可以通过单独的参数以通常的方式调用。它的工作方式类似于 java 脚本中的扩展运算符,可以接受多个参数。例如:-

func main(){
  generateReport(1,2,3,4)
}

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

关于Go可变函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48849493/

相关文章:

google-app-engine - 构建约束应用引擎 golang

multithreading - 为什么 goroutine 分配在多核上会变慢?

GO 获取 K8S api 服务器健康状态

postgresql - IN pq.Array 传递值失败

arrays - 在 Go 中附加 2 维 slice

mysql - MySql 的 Golang ORDER BY 问题

go - 向 TCP 服务器发送多个请求失败

go - 在另一个函数中更改golang slice

function - 语法错误 : Non-declaration statement outside function body

go - 如何将断言临时结构键入具体结构