Go语言编程-v100.pdf
Go!why404七牛云存储2012/07/21112年7月21日星期六What?Godaddy(去你爹,X)Go a head(去个头,X)Golang(Go语言,YES)212年7月21日星期六Go a head.312年7月21日星期六Golang is一个在语言层面实现了并发机制的类C通用型编程语言412年7月21日星期六为什么我们需要一门新语言多核时代,硬件更新换代快软件不能充分利用硬件资源传统编程语言多核并发编程够繁琐生产效率512年7月21日星期六Go前世今生1995 Bell Labs,Plan9-Inferno(Limbo)2007/09 Googles 20%project2008/05 Google full-time project 2009/11 officially announced2012/03 Go1 Released612年7月21日星期六Hello Worldpackage mainimport“fmt”func main()fmt.Println(“Hello,世界”)712年7月21日星期六Hello Worldpackage mainimport“fmt”func main()fmt.Println(“Hello,世界”)export GOROOT=$HOME/goexport PATH=$PATH:$GOROOT/bin$go run hello.goHello,世界812年7月21日星期六Hello Worldpackage mainimport“fmt”func main()fmt.Println(“Hello,世界”)export GOROOT=$HOME/goexport PATH=$PATH:$GOROOT/bin$go build hello.go$./helloHello,世界912年7月21日星期六Go特性小结(1)动态语言的写法,静态类型,编译执行模块化的包管理机制,一个脚本即可是一个包包可导出可见成员供包外部使用Go程序执行首调 main.main()函数任何地方都是UTF-8的包括字符串和程序代码1012年7月21日星期六变量var a intvar b stringvar c bool1112年7月21日星期六同时声明多个变量var a intvar b stringvar c boolvar(a int b string c bool)1212年7月21日星期六声明多个同类型变量var a intvar a1 intvar a,a1 int1312年7月21日星期六变量声明默认零值初始化var a int /a=0var b string/b=“”var c bool /c=false1412年7月21日星期六变量声明并赋值var a int=99var b string=“hello”var c bool=falsevar a intvar b stringvar c boola=99b=“hello”c=false1512年7月21日星期六变量声明并赋值(简写)var a int=99var b string=“hello”var c bool=falsea:=99b:=“hello”c:=false(:=仅限函数内使用)1612年7月21日星期六变量声明且并行赋值var a,a1 inta,a1=99,100a,a1:=99,100(:=仅限函数内使用)1712年7月21日星期六匿名变量 _var a,a1 int_,a1=99,100_,a1:=99,100(将100赋值给 a1,同时丢弃99)1812年7月21日星期六声明却未使用的变量package mainfunc main()var a string对声明却未赋值的变量,会导致程序编译失败1912年7月21日星期六Go特性小结(2)变量声明,类型后置,默认零值初始化同类型的多个变量,可在一行内完成声明函数内支持变量同时声明并赋值支持多个变量并行赋值支持匿名变量Go的静态编译是语法检查的第一道单元测试2012年7月21日星期六基本类型bool(true,false)数字内型(有符号/无符号,有长度/无长度)string(内建”UTF-8 string”)array(n)slice(arrayi:j)map(map)chanerror2112年7月21日星期六数字类型无长度int,uint有长度int8,int16,int32,int64byte/uint8,uint16,uint32,uint64float32,float642212年7月21日星期六强类型转换(1)var a intvar b int32a=99b=a+1 /Errorb=b+1 /OKb=int32(a)+1/OK2312年7月21日星期六强类型转换(2)var s string=“hello”s0=a/Error/OKs1:=byte(s)s10=as2:=string(s1)字符串一旦定义,不可修改。字符串是字符的序列,不是字节的序列。2412年7月21日星期六多行字符串s1:=“line1.”+“line2.”/ors2:=line1.line2.2512年7月21日星期六常量常量的值只能是 bool、string 或数字类型中的一种。常量名大小写无所谓。const a=99/orconst(a=99 b string=“hello”/类型可选传入)2612年7月21日星期六array定义方式:n,值类型var arr 10intarr0=1arr1=2a1:=.1,2,3a2:=22int 2int1,2,2int3,4 a3:=22int.int1,2,.int3,4 a4:=22int 1,2,3,4 2712年7月21日星期六slice动态数组,引用类型var s=make(,n)s:=arri:j/=arri-arrj-1a:=.int1,2,3,4,5/序号0-4s1:=a2:4/序号2-3,返回3,4s2:=a:/=a0:len(a)s3:=a:4/=a0:4s4:=s1:/=s10:len(s1),-&a2812年7月21日星期六slice appends0:=int0,0s1:=append(s0,1)/int0,0,1s2:=append(s1,s0.)/int0,0,1,0,02912年7月21日星期六slice copyvar a=.int0,1,2,3var s=make(int,2)n1:=copy(s,a0:)/n1=2,s=int0,1n2:=copy(s,a2:)/n2=2,s=int2,33012年7月21日星期六map定义:map声明:make(map)m:=mapstringint“a”:1,”b”:2,”c”:3/遍历for k,v:=range m /.3112年7月21日星期六map/查询v,ok:=m“d”/v=0,ok=false/删除delete m“a”3212年7月21日星期六Go特性小结(3)Go是强类型语言,Duck TypeGo内建 string,slice,map 类型string 是UTF-8的字符序列,非字节序列slice 是指针传递而不是像array值拷贝更高效3312年7月21日星期六控制语句ifswitchfor支持 break,contine 关键字3412年7月21日星期六ifif x 0 retun y else retun xif err:=os.Open(file);err!=nil return errdoSomething(f)3512年7月21日星期六switchswitch case,:/.case:/.default:/.3612年7月21日星期六fallthroughswitch i case 0:case 1:do()/如果i=0该函数不被调用switch i case 0:fallthrough case 1:do()/如果i=0该函数会被调用3712年7月21日星期六forfor init;condition;post /计数循环for condition /while 循环for /for;死循环3812年7月21日星期六forsum:=0for i:=0;i 10;i+sum+=i list:=stringa,b,cfor k,v:=range list /.3912年7月21日星期六Go特性小结(4)简单、清晰的流程控制只有 if,switch,for4012年7月21日星期六函数func(p T)funcname(i1 T1,i2 T2)(o Tn,err Error)/return.4112年7月21日星期六函数func add(x int,y int)(r int)r=x+y returnfunc add(x,y int)int return x+y4212年7月21日星期六gotofunc myfunc()i:=0Here:fmt.Println(i)i+goto Here4312年7月21日星期六deferfunc CopyFile(dstName,srcName string)(written int64,err error)src,err:=os.Open(srcName,os.O_RDONLY,0)if err!=nil return defer src.Close()dst,err:=os.Open(dstName,os.O_WRONLY|os.O_CREATE,0644)if err!=nil return defer dst.Close()return io.Copy(dst,src)4412年7月21日星期六匿名函数(闭包)func c()(i int)defer func()i+()return 14512年7月21日星期六Panic and Recoverfunc check(err error)?if err!=nil?panic(err)?func safeHandler(fn http.HandlerFunc)http.HandlerFunc?return func(w http.ResponseWriter,r*http.Request)?defer func()?if e,ok:=recover().(error);ok?http.Error(w,e.Error(),http.StatusInternalServerError)?log.Panic(panic fired in%v.panic-%v,fn,e)?log.Panic(string(debug.Stack()?()?fn(w,r)?mux.HandleFunc(/,safeHandler(func(w http.ResponseWriter,r*http.Request)app.pageHandler(w,r)4612年7月21日星期六Go特性小结(5)Go函数支持命名返回参数,声明较语义化goto(代码复用)defer(程序安全)匿名函数4712年7月21日星期六结构体(Struct)type Point struct x,y float64var p Pointp.x=123p.y=456.78var p1*Point=new(Point)*p1=pp1.x=123.45/(*p1).x4812年7月21日星期六new()vs make()new()返回指针t:=new(T)make()返回初始化值用于创建 slices,maps,channels4912年7月21日星期六面向对象type Point struct x,y intfunc(p*Point)Get()(int,int)/Public return p.x,p.yfunc(p*Point)Put(x,y int)/Public p.x=x p.y=yfunc(p*Point)add(x,y int)int /private return p.x+p.y5012年7月21日星期六模拟继承type YetAnotherPointer struct Point/匿名字段 z intfunc(p*YetAnotherPointer)Get()(int,int,int)return p.x,p.y,p.zm:=YetAnotherPointerPointer1,2,3fmt.Println(m.Get()5112年7月21日星期六接口type Pointer interface Get()(int,int)Put(x,y int)type Point struct x,y intfunc(p*Point)Get()(int,int)return p.x,p.yfunc(p*Point)Put(x,y int)p.x=x p.y=y5212年7月21日星期六Goroutine(1)func ready(w string,sec int64)secs:=time.Duration(sec)*time.Second time.Sleep(secs)fmt.Println(w,is ready!)func main()go ready(Tee,2)go ready(Coffee,1)fmt.Println(Im waiting)secs:=time.Duration(sec)*time.Second time.Sleep(5*secs)Output:Im waiting /立刻Coffee is ready/1秒后Tee is ready /2秒后5312年7月21日星期六Goroutine(2)Goroutines 缺省是并发执行的,但不是并行运行的,同一时刻只有一个goroutine执行。runtime.GOMAXPROCS(n)GOMAXPROCS environment varaible5412年7月21日星期六Channelc:=make(chan int)c-1 /发送整数 1 到 channel c-c /从 channel c接值,并丢弃i:=-c /接值,并初始化赋值给变量i5512年7月21日星期六Channelvar c chan intfunc ready(w string,sec int64)secs:=time.Duration(sec)*time.Second time.Sleep(secs)fmt.Println(w,is ready!)c-1func main()c=make(chan int)go ready(Tee,2)go ready(Coffee,1)fmt.Println(Im waiting)ret:=-c ret=-c5612年7月21日星期六More.5712年7月21日星期六Q&A飞天急速徐倒立5812年7月21日星期六