變參,本質上是一個切片,只能接受一到多個同類型參數,且必須放到參數列表尾部.
將切片作爲變參時,須進行展開操作,如果是數組,先將其轉換爲切片。
如果需要對多個數組或切片裏的元素進行相同的數據處理,這時就可以運用變參,將數組或切片作爲參數傳遞進函數裏。
package main
import(
"fmt"
)
func test_bianchan(a ...int) {
for i := range a {
a[i] += 100
}
}
func main() {
a := []int{10, 20, 30}
b :=[]int{35,22,65,38,68,132,310}
test_bianchan(a...) //...的意思是將這個切片展開並將元素傳遞給函數變參
fmt.Println(a)
text_bianchan(b...)
fmt.Println(b)
}