Go语言:slice扩容时如何自动将元素作为函数参数传入?
在Go中自动将slice所有元素作为函数参数传入的方法
你可以利用Go的可变参数展开语法实现这个需求,无需手动逐个指定slice元素作为参数。
fmt.Println本身支持接收可变数量的参数,当你持有一个slice时,只需在slice变量后加上...,就能把slice里的每个元素自动拆解为独立参数传入函数,不管slice后续扩容新增多少元素,都能自动适配。
修改你的increaseArguments函数如下:
func increaseArguments(b []string) { fmt.Println(b...) }
完整运行代码:
package main import "fmt" func main() { var a []string a = append(a, "this", "this2", "this3") increaseArguments(a) a = append(a, "this4") increaseArguments(a) } func increaseArguments(b []string) { fmt.Println(b...) }
运行后输出:
this this2 this3 this this2 this3 this4
原理说明:
fmt.Println的函数签名是func Println(a ...interface{}) (n int, err error),其中...interface{}表示接受任意数量的任意类型参数- 对于
[]string类型的slice,由于string可以隐式转换为interface{},直接用b...就能将slice的所有元素展开,逐个传入fmt.Println,完全适配slice的动态长度变化。
内容的提问来源于stack exchange,提问作者user18572278
相关产品推荐
相关产品推荐

