gpt4 book ai didi

Go可变函数参数传递

转载 作者:IT王子 更新时间:2023-10-29 00:50:49 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com