基本语法
:=
Inside a function, the
:=
short assignment statement can be used in place of avar
declaration with implicit type.Outside a function, every statement begins with a keyword (
var
,func
, and so on) and so the:=
construct is not available.
切片 = 数组引用
1 | func main() { |
结构体切片初始化
1 | func main() { |
这个赋值之后还是它?
1 | package main |
nil
切片的零值是 nil
。
make创造切片
make
函数会分配一个元素为零值的数组并返回一个引用了它的切片:
1 | b := make([]int, 0, 5) // len(b)=0, cap(b)=5 |
append内建函数
向元素类型为T
的切片s
中追加同类型元素,返回该类型的切片。
1 | func append(s []T, vs ...T) []T |
range
for
循环的 range
形式可遍历切片或映射。
当使用 for
循环遍历切片时,每次迭代都会返回两个值。第一个值为当前元素的下标,第二个值为该下标所对应元素的一份副本。
1 | var pow = []int {1, 2} |