标签:可变 for imp Golan code end class 今天 result
之前提到了把一个切片追加到另外一个切片时使用到了...
今天我们好好研究一下这三个点,博客写着写着又成了,回字有四种写法
1 package main 2 3 import "fmt" 4 5 func main() { 6 fmt.Println(Sum(1, 4, 6, 7)) 7 } 8 9 func Sum(numbers ...int) int { 10 result := 0 11 for _, n := range numbers { 12 result += n 13 } 14 return result 15 }
第9行代码定义了一个Sum函数,使用了一个可变长的参数numbers。我们在调用的时候,可以传入任意个指定类型的参数。
1 package main 2 3 import "fmt" 4 5 func main() { 6 fmt.Println(Sum(1, 4, 6, 7)) 7 fmt.Println(Sum([]int{2, 3, 5}...)) 8 } 9 10 func Sum(numbers ...int) int { 11 result := 0 12 for _, n := range numbers { 13 result += n 14 } 15 return result 16 }
这样就不需要一个一个的把slice的元素打出来了
a := [...]int{1, 3, 6}
6 a := [...]string{"a", "b", "c", "d", "e"}
7 b := a[1:2]
8 fmt.Printf("length of slice %d capacity %d\n", len(b), cap(b)) //length is 1 and capacity is 4
9 b = append(b, "x", "y", "z", "m", "n")
10 fmt.Printf("length of slice %d capacity %d\n", len(b), cap(b)) //length is 1 and capacity is 8
标签:可变 for imp Golan code end class 今天 result
原文地址:https://www.cnblogs.com/13579net/p/10102167.html