本文共 2339 字,大约阅读时间需要 7 分钟。
:推荐两倍速观看
上述B站视频的对应博客//第一种var name string = "Alice"//第二种var name = "Alice"//第三种,只能在函数中使用 name := "Alice"
iota
关键字是按照行来计数的,每增加一行就会加1float
默认类型是float64
,float32
和float64
之间不能相互赋值str := "哈哈哈,I am a student" s1 := []rune(str) //把字符串强制转换为一个run切片 s1[1] = '中' fmt.Println(string(s1)) //将切片转换为字符串,输出为 哈中哈,I am a student
rune
在本质上是一个int32
类型的int32
for range
遍历数组、切片、字符串、map及通道arr := [...]int{ 1,2,3,4,5,6,7,8,9,10}
==
和!=
运算符切片(Slice
)是一个拥有相同类型元素的可变长度的序列。它是基于数组类型做的一层封装。它非常灵活,支持自动扩容。
切片是一个引用类型
,它的内部结构包含地址、长度和容量。切片一般用于快速地操作一块数据集合
//切片声明var name []T//make函数构造切片make([]T, size, cap)/*T:切片的元素类型size:切片中元素的数量cap:切片的容量*/
切片的扩容原理:代码在src/runtime/slice.go
下
newcap := old.capdoublecap := newcap + newcapif cap > doublecap { newcap = cap} else { if old.len < 1024 { newcap = doublecap } else { // Check 0 < newcap to detect overflow // and prevent an infinite loop. for 0 < newcap && newcap < cap { newcap += newcap / 4 } // Set newcap to the requested cap when // the newcap calculation overflowed. if newcap <= 0 { newcap = cap } }}
import "fmt"func main() { function(f1)}func f1() int { return 10}func function(x func() int) func(int,int) int{ ret := func(a,b int) int{ return a+b } return ret}
上述函数function
的传入参数可以是函数,但这个函数的返回值需要是int
类型;function
的返回值也是函数,返回的这个函数需要满足两个int类型参数,和int类型返回值
()
表示立即执行,一般适用于只使用一次的情况func main() { f1 := func(a,b int) { println(a+b) } f1(2,3) func(a,b int){ println(a+b) }(1,2)}
func f1(f func()) { fmt.Println("f1执行了")}func f2(x,y int) { fmt.Println("f2执行了") fmt.Println(x+y)}//f3 修改后的函数func f3(f func(int,int),x,y int) func() { tmp := func() { //fmt.Println(x+y) f(x,y) } return tmp}
func main() { rand.Seed(time.Now().UnixNano()) //生成随机数种子 fmt.Println(rand.Int())}
转载地址:http://iwjqb.baihongyu.com/