go语言的方法没用花哨的方法重载之类的,没有默认参数,没有可选参数,只有一个可变参数
...interface{} 参数就表示要接受一个interface{}的切片类型,可以理解为 []interface{}
nums如果用…展开,就表示是一个切片,如果不展开,就表示是一个切片中的一个元素
可以将int切片作为一个元素赋给interface{}数组, 不能将一个int切片转化为interface{}切片
如果不加…,就表示参数…int切片中的一个元素,但是nums[:]本身是切片,切片是不能作为int切片的一个元素的
…将参数转化为切片
比如:
func TestArgs(f int, arg ...interface{}){
fmt.Println(f, arg)
}
func main(){
nums := []int{1,2,3,4}
nums2 := []interface{}{5,6,7,8}
TestArgs(nums) // error:
TestArgs(1, nums) // 1 [[1 2 3 4]]
TestArgs(1, nums...) // 1 [1 2 3 4]
TestArgs(1, nums,nums2) // 1 [[1 2 3 4] [5 6 7 8]]
}
...interface{} 参数就表示要接受一个interface{}的切片类型,可以理解为 []interface{}
nums如果用…展开,就表示是一个切片,如果不展开,就表示是一个切片中的一个元素
func TestArgs(f int, arg ...interface{}){
fmt.Println(f, arg)
}
func main(){
nums := []int{1,2,3,4}
TestArgs(1, nums) // 1 [[1 2 3 4]]
TestArgs(1, nums...) // error: cannot use "nums"(type []int) as type []interface{}
}
可以将int切片作为一个元素赋给interface{}数组, 不能将一个int切片转化为interface{}切片
func TestArgs(f int, arg ...int){
fmt.Println(f, arg)
}
func main(){
nums := []int{1,2,3,4}
TestArgs(1, nums[:]) // error :cannot use "nums"(type []int) as type int
TestArgs(1, 2) // 1 [2]
TestArgs(1, nums...) // 1 [1 2 3 4]
}
如果不加…,就表示参数…int切片中的一个元素,但是nums[:]本身是切片,切片是不能作为int切片的一个元素的
…将参数转化为切片
比如:
func append(slice []Type, elems ...Type) []Type
使用
func main() {
s1 := []int{1, 2, 3}
s2 := []int{4, 5}
s1 = append(s1, s2...) //而不是 s1 = append(s1, s2)
fmt.Println(s1) // [1 2 3 4 5]
}