golang只有25个关键字
package: 定义包名,go中任何一个文件必须有一个package,一般而言,package的定义和文件所属文件夹一致,并且main函数所在文件的package必须是main
import: 导入包名的关键字
const: 声明常量的关键字
var: 声明变量的关键字
func: 定义函数关键字(结构体方法其本质也是函数)
defer: 延迟执行(预加载)关键字(在关闭资源场景中最常使用,以免忘记关闭资源).
go: 并发关键字
return: 函数返回
struct: 定义结构体
interface: 定义接口(所有变量都实现空接口)
map: 声明创建map类型关键字
chan: 声明创建chan类型关键字
以及一些控制流程的关键字
if,else,for,range,break,continue
swich,select,case,fallthrough,default
type: 这个关键字非常常用,定义结构体,类型等
goto: 跳转语句关键字
if else: 控制结构
//-----------------------------------------------------------------------------------------------------------------
package main
import (
"fmt"
"time"
)
var testVar1 = 0 //自动识别类型
var testChanVar chan *user
const (
testIota1 int = iota //初始化为0
testIota2 //不写表达式 视为上一个表达式,等价于 testIota2 int = iota
testIota3 int = 9
testIota4
testIota5 int = iota //iota只有出了所属的const() 才重置为0
)
type user struct {
name string
age int
}
func testMap() {
fmt.Printf("this is testMap...n")
tMap := make(map[string]interface{},4) //value的类型是空接口类型,所有类型都实现了空接口,所以value的值可以是任意类型.
tMap["name"] = "xzk"
tMap["age"] = 25
for key,value := range tMap {
fmt.Printf("key=%v,value=%vn",key,value) //无序,每次打印的顺序不一样
switch key { //switch 后可以没有变量,那么case可以是表达式,相当于if else
case "name":
fmt.Printf("this is swith case name...n")
fallthrough //上一个case命中后,强制执行下一个case(不管一下个case是否命中)
case "fallthrough":
fmt.Printf("this is fallthrough...n")
default:
fmt.Printf("this is default...n")
}
}
}
func pushChan() {
fmt.Printf("this is pushChan...n")
userBean := &user{
name: "xzk",
age: 18,
}
select {
case testChanVar <- userBean: //如果通道未满,将数据放入通道
default:
fmt.Printf("testChanVar chan overflow,size=%d,data=%vn",cap(testChanVar),userBean)
}
}
func getChanData() {
fmt.Printf("this is getChanData start...n")
testChanVar = make(chan *user,1000) //初始化大小为1000的通道
for userBean := range testChanVar { //遍历通道,取出数据
fmt.Printf("this is getChanData...,userBeanName=%sn",userBean.name)
}
}
func init() {
go getChanData() //异步执行getChanData()函数
fmt.Printf("this is init end...n")
}
func main() {
fmt.Printf("this is main start...n")
defer fmt.Printf("this is defer...n") //延迟执行. 预加载之后,return之前执行. 通常用于关闭资源.
// 使用时需要注意 引用变量和值变量 的区别(return语句实际上也是分2个步骤. 1:设置返回值,2:真正的return. defer是在中间执行)
go pushChan()
go testMap()
for {
fmt.Printf("this is main...%dn",testIota5)
time.Sleep(time.Second)
testVar1++
if testVar1 == testIota5 {
break
}
}
fmt.Printf("this is main end...n") //main函数退出,go异步线程随之结束
}
//------------控制台打印结果---------------------------------------
this is init end...this is getChanData start...this is main start...this is pushChan...this is main...4this is getChanData...,userBeanName=xzkthis is testMap...key=age,value=25this is default...key=name,value=xzkthis is swith case name...this is fallthrough...this is main...4this is main...4this is main...4this is main end...this is defer...