Go语言实战 (William,Kennedy 等著)
第1章 关于Go语言的介绍 (已看)
1.1 用Go解决现代编程难题
1.1.1 开发速度
1.1.2 并发
1. goroutine
2. 通道
1.1.3 Go语言的类型系统
1. 类型简单
2. Go接口对一组行为建模
1.1.4 内存管理
1.2 你好,Go
介绍Go playground
第2章 快速开始一个Go程序
2.1 程序架构
2.2 main包
2.3 search包
2.3.1 search.go
2.3.2 feed.go
2.3.3 match.go/default.go
2.4 RSS匹配器
2.5 小结
第3章 打包和工具链 (已看)
3.1 包
3.1.1 包名惯例
3.1.2 main包
3.2 导入
3.2.1 远程导入
3.2.2 命名导入
3.3 函数init
3.4 使用Go的工具
package main import ( "fmt" "chapter3/words" "io/ioutil" "os" ) func main() { filename := os.Args[] contents,err := ioutil.ReadFile(filename) if err != nil { fmt.Println(err) return } text := string(contents) count := words.CountWords(text) fmt.Printf("There are %d word in your text. \n",count) }
3.5 进一步介绍Go开发工具
3.5.1 go vet
3.5.2 Go代码格式化
3.5.3 Go语言的文档
1. 从命令行获取文档
2. 浏览文档
3.6 与其他Go开发者合作
以分享为目的创建代码库
1. 包应该在代码库的根目录中
2. 包可以非常小
3. 对代码执行go fmt
4. 给代码写文档
3.7 依赖管理
3.7.1 第三方依赖
3.7.2 对gb的介绍
3.8 小结
第4章 数组,切片和映射 (已看)
4.1 数组的内部实现和基础功能
]int array := [],,,,} array := [...],,,,} array := []:,:} array := []{,,,,} array[] = array := []*::new(int)} *array[] = *array[] = ]string array2 := []string{"Red","Blue","Green","Yellow","Pink"} array1 = array2 ]string array2 := []string{"Red","Blue","Green","Yellow","Pink"} array1 = array2 Compiler Error: cannot use array2 (type []]string in assignment ]*string array2 := []*string{new(string),new(string),new(string)} *array2[] = "Red" *array2[] = "Blue" *array2[] = "Green" array1 = array2 ][]int array := [][],},{,},{,},{,}} array := [][]:{,},:{,}} array := [][]:{:},{:}} ][]int array[][] = array[][] = array[][] = array[][] = ][]int ][]int array2[][] = array2[][] = array2[][] = array2[][] = array1 = array2 ]] ][] var array [1e6]int foo(array) func foo(array [1e6]int) { ... } var array [1e6]int foo(&array) func foo(array *[1e6]int) { ... }
4.1.1 内部实现
4.1.2 声明和初始化
4.1.3 使用数组
4.1.4 多维数组
4.1.5 在函数间传递数组
4.2 切片的内部实现和基础功能
slice := make([]) slice := make([],) slice := make([],) Compiler Error: len larger than cap in make([]int) slice := []string{"Red","Blue","Green","Yellow","Pink"} slice := [],,} slice := []:""} array := [],,} slice := [],,} var slice []int // 创建nil整型切片 slice := make([]) slice := []int{} slice := [],,,,} slice[] = slice := [],,,,} newSlice := slice[:] newSLice[] = slice := [],,,,} newSlice := slice[:] newSlice[] = Runtime Exception: panic: runtime error: index out of range slice := [],,,,} newSlice := slice[:] newSlice = append(newSlice,) slice := [],,,} newSlice := append(slice,) souce := []string{"Apple","Orange","Plum","Banana","Grape"} slice := source[::] slice := source[::] Runtime Error: panic: runtime error: slice bounds out of range s1 := [],} s2 := [],} fmt.Printf("%v\n",append(s1,s2...)) Output: [ ] slice := [],,,} for index,value := range slice { fmt.Printf("Index: %d value: %d\n",index,value) } Output: Index: Value: Index: Value: Index: Value: Index: Value: slice := [],,,} for index,value := range slice { fmt.Printf("Value: %d Value-Addr: %X ElementAddr: %X\n", value,&value,&slice[index]) } Output: Value: Value-Addr: ElemAddr: 1052E100 Value: Value-Addr: ElemAddr: 1052E104 slice := [],,,} ;index < len(slice);index++ { fmt.Printf("Index: %d Value:%d\n",index,slice[index]) } slice := [][]},{,}} slice := [][]},{,}} slice[] = append(slice[],) slice := make([]int,1e6) slice = foo(slice) func foo(slice []int) []int { ... return slice }
4.2.1 内部实现
4.2.2 创建和初始化
1. make和切片字面量
2. nil和空切片
4.2.3 使用切片
1. 赋值和切片
2. 切片增长
3. 创建切片时的3个索引
4. 迭代切片
4.2.4 多维切片
4.25 在函数间传递切片
4.3 映射的内部实现和基础功能
dict := make(map[string]int) dict := map[string]string{"Red":"#da1137","Orange":"#e95a22"} dict := map[[]string]int{} Compiler Exception: invalid map key type []string dict := map[int][]sting{} colors := map[string]string{} colors["Red"] = "#da1337" var colors map[string]string colors["Red"] = "#da1337" Runtime Error: panic: runtime error: assignment to entry in nil map value,exsits := colors["Blue"] if exists { fmt.Println(value) } value := colors["Blue"] if value != "" { fmt.Println(value) } colors := map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen":"#228b22", } for key,value := range colors { fmt.Printf("Key: %s Value: %s\n",key,value) } delete(colors,"Coral") for key,value := range colors { fmt.Printf("Key: %s Value: %s\n",key,value) } func main() { colors: = map[string]string { "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } for key,value := range colors { fmt.Printf("Key: %s Value: %s\n",key,value) } removeColor(colors,"Coral") for key,value := range colors { fmt.Printf("Key: %s Value: %s\n",key,value) } } func removeColor(colors map[string]string,key string) { delete(colors,key) }
4.3.1 内部实现
4.3.2 创建和初始化
4.3.3 使用映射
4.3.4 在函数间传递映射
4.4 小结
第5章 Go语言的类型系统 (已看)
5.1 用户定义的类型
type user struct { name string email string ext int privileged bool } var bill user lisa := user{ name: "Lisa", email: "lisa@email.com", ext:, privileged:true, } user{ name: "Lisa", email:"lisa@email.com", ext:, priviledged:true, } lisa := user{,true} type admin struct { person user level string } fred := admin{ person:user { name: "Lisa", email: "lisa@email.com", ext: , priviledged:true, }, level:"super", } type Duration int64 package main type Duration int64 func main() { var dur Duration dur = int64() } cannot use int64() (type in64) as type Duration in assignment
5.2 方法
package main import ( "fmt" ) type user struct { name string email string } func (u user) notify() { fmt.Printf("Sending User Email To %s<%s>\n",u.name,u.email) } func (u *user) changeEmail(email string) { u.email = email } func main() { // user类型的值可以用来调用使用值接收者声明的方法 bill := user{"Bill","bill@email.com"} bill.notify() // 指向user类型值的指针也可以用来调用使用值接收者声明的方法 lisa := &user{"Lisa","lisa@email.com"} lisa.notify() (*lisa).notify() // user类型的值可以用来调用使用指针接收者声明的方法 bill.changeEmail("bill@newdomain.com") (&bill).changeEmail("bill@newdomain.com") bill.notify() // 指向user类型值的指针可以用来调用使用指针接收者声明的方法 lisa.changeEmail("lisa@newdomain.com") lisa.notify() }
5.3 类型的本质
type Time struct { sec int64 nsec int32 loc *Location } func Now() Time { sec,nsec := now() return Time{sec + unixToInternal,nsec,Local} } func (t Time) Add(d Duration) Time { t.sec += int64(d/1e9) nsec := int32(t.nsec) + int32(d%1e9) if nesc >= 1e9 { t.sec++ nsec -= 1e9 } { t.sec-- nsec += 1e9 } t.nsec = nsec return t } type File struct { *file } type file struct { fd int name string dirinfo *dirInfo nepipe int32 } func Open(name string) (file *File,err error) { ) } func (f *File) Chdir() error { if f == nil { return ErrInvalid } if e := syscall.Fchdir(f.fd); e != nil { return &PathError{"chdir",f.name,e} } return nil }
5.3.1 内置类型
5.3.2 引用类型
5.3.3 结构类型
5.4 接口
package main import ( "fmt" "io" "net/http" "os" ) func init() { { fmt.Println("Usage: ./example2 <url>") os.Exit(-) } } func main() { r,err := http.Get(os.Args[]) if err != nil { fmt.Println(err) return } io.Copy(os.Stdout,r.Body) if err := r.Body.Close(); err != nil { fmt.Println(err) } } package main import ( "bytes" "fmt" "io" "os" ) func main() { var b bytes.Buffer b.Write([]byte("Hello")) fmt.Fprintf(&b,"World!") io.Copy(os.Stdout,&b) } package main import ( "fmt" ) type notifier interface { notify() } type user struct { name string email string } func (u *user) notify() { fmt.Printf("Sending user email to %s<%s>\n",u.name,u.email) } func main() { u := user{"Bill","bill@email.com"} sendNotification(&u) } func sendNotification(n notifier) { n.notify() } package main import ( "fmt" ) type notifier interface { notify() } type user struct { name string email string } func (u *user) notify() { fmt.Printf("Sending user email to %s<%s>\n",u.name,u.email) } type admin struct { name string email string } func (a *admin) notify() { fmt.Printf("Sending admin email to %s<%s>\n",a.name,a.email) } func main () { bil := user{"Bill","bill@email.com"} sendNotification(&bill) lisa := admin{"Lisa","lisa@email.com"} sendNotification(&lisa) } func sendNotification(n notifier) { n.notify() }
5.4.1 标准库
5.4.2 实现
5.4.3 方法集
5.4.4 多态
5.5 嵌入类型
package main import ( "fmt" ) type user struct { name string email string } func (u *user) notify() { fmt.Printf("Sending user email to %s<%s>\n",u.name,u.email) } type admin struct { user level string } func main() { ad := admin { user: user{ name: "john smith", email: "john@yahoo.com", }, level: "super" } ad.user.notify() ad.notify() } package main import ( "fmt" ) type notifier interface { notify() } type user struct { name string email string } func (u *user) notify() { fmt.Printf("Sending user email to %s<%s>\n",u.name,u.email) } type admin struct { user level string } func main() { ad := admin{ user: user{ name: "john smith", email: "john@yahoo.com", }, level: "super", } sendNotification(&ad) } func sendNotification(n notifier) { n.notify() }
5.6 公开或未公开的标识符
5.7 小结
第6章 并发
6.1 并发与并行
6.2 goroutine
package main import ( "runtime" "sync" "fmt" ) func main() { runtime.GOMAXPROCS() var wg sync.WaitGroup wg.Add() fmt.Println("Start Gorountines") go func() { defer wg.Done() ; count < ; count++ { ; char++ { fmt.Printf("%c ",char) } } }() go func() { defer wg.Done() ; count < ; count++ { ; char++ { fmt.Printf("%c ",char) } } }() fmt.Println("Waiting To Finish") wg.Wait() fmt.Println("\nTerminating Program") } package main import ( "sync" "runtime" "fmt" ) var wg sync.WaitGroup func main() { runtime.GOMAXPROCS(runtime.NumCPU()) wg.Add() fmt.Println("Create Goroutines") go printPrime("A") go printPrime("B") fmt.Println("Waiting To Finish") wg.Wait() fmt.Println("Terminating Program") } func printPrime(prefix string) { defer wg.Done() next: ; outer < ; outer++ { ; inner < outer; inner++ { { continue next } } fmt.Printf("%s:%d\n",prefix,outer) } fmt.Println("Completed",prefix) }
6.3 竞争状态
// 这个示例程序展示如何在程序里造成竞争状态 // 实际上不希望出现这种情况 package main import ( "sync" "runtime" "fmt" ) var ( counter int wg sync.WaitGroup ) func main() { wg.Add() go incCounter() go incCounter() wg.Wait() fmt.Println("Final Counter:",counter) } func incCounter(id int) { defer wg.Done() ; count < ; count++ { value := counter runtime.Gosched() value++ counter = value } }
6.4 锁住共享资源
6.4.1 原子函数
package main import ( "sync" "fmt" "time" "sync/atomic" ) var ( shutdown int64 wg sync.WaitGroup ) func main() { wg.Add() go doWork("A") go doWork("B") time.Sleep( * time.Second) fmt.Println("Shutdown Now") atomic.StoreInt64(&shutdown,) wg.Wait() } func doWork(name string) { defer wg.Done() for { fmt.Printf("Doing %s Work\n",name) time.Sleep( * time.Millisecond) { fmt.Printf("Shutting %s Down\n",name) break } } }
6.4.2 互斥锁
package main import ( "sync" "runtime" "fmt" ) var ( counter int wg sync.WaitGroup mutex sync.Mutex ) func main() { wg.Add() go incCounter() go incCounter() wg.Wait() fmt.Printf("Final Counter: %d\n",counter) } func incCounter(id int) { defer wg.Done() ; count < ; count++ { mutex.Lock() { value := counter runtime.Gosched() value++ counter = value } mutex.Unlock() } }
6.5 通道
6.5.1 无缓冲的通道
package main import ( "sync" "fmt" "math/rand" "time" ) var wg sync.WaitGroup func init() { rand.Seed(time.Now().UnixNano()) } func main() { court := make(chan int) wg.Add() go player("Nadal",court) go player("Djokovic",court) court <- wg.Wait() } func player(name string,court chan int) { defer wg.Done() for { ball,ok := <-court if !ok { fmt.Printf("Player %s Won\n",name) } n := rand.Intn() == { fmt.Printf("number=%s Player %s Missed\n",n,name) close(court) return } fmt.Printf("Player %s Hit %d\n",name,ball) ball++ court <- ball } } package main import ( "sync" "fmt" "time" ) var wg sync.WaitGroup func main() { baton := make(chan int) wg.Add() go Runner(baton) baton<- wg.Wait() } func Runner(baton chan int) { var newRunner int runner := <-baton fmt.Printf("Runner %d Running With Baton\n",runner) { newRunner = runner + fmt.Printf("Runner %d To The Line\n",newRunner) go Runner(baton) } time.Sleep( * time.Millisecond) { fmt.Printf("Runner %d Finished,Race Over\n",runner) wg.Done() return } fmt.Printf("Runner %d Exchange With Runner %d\n",runner,newRunner) baton <-newRunner }
6.5.2 有缓冲的通道
package main import ( "sync" "math/rand" "time" "fmt" ) const ( numberGoroutines = taskLoad = ) var wg sync.WaitGroup func int() { rand.Seed(time.Now().Unix()) } func main() { tasks := make(chan string,taskLoad) wg.Add(numberGoroutines) ; gr <= numberGoroutines; gr++ { go worker(tasks,int64(gr)) } ; post <= taskLoad; post++ { tasks <- fmt.Sprintf("Task: %d",post) } close(tasks) wg.Wait() } func worker(tasks chan string,worker int64){ defer wg.Done() for { task,ok := <-tasks if !ok { fmt.Printf("Worker: %d : Shutting Down\n",worker) return } fmt.Printf("Worker: %d : Started %s\n",worker,task) sleep := rand.Int63n() time.Sleep(time.Duration(sleep) * time.Millisecond) fmt.Print("Worker: %d : Completed %s\n",worker,task) } }
第7章 并发模式
7.1 runner
7.2 pool
7.3 work
7.4 小结
第8章 标准库
8.1 文档与源代码
8.2 记录日志
8.2.1 log包
8.2.2 定制的日志记录器
8.2.3 结论
8.3 编码/解码
8.3.1 解码JSON
8.3.2 编码JSON
8.3.3 结论
8.4 输入和输出
8.4.1 Writer和Reader接口
8.4.2 整合并完成工作
8.4.3 简单的curl
8.4.4 结论
8.5 小结
第9章 测试和性能
9.1 单元测试
9.1.1 基础单元测试
9.1.2 表组测试
9.1.3 模仿调用
9.1.4 测试服务端点
9.2 示例
9.3 基准测试
9.4 小结
Go语言实战 (William,Kennedy 等著)的更多相关文章
- 《Go语言实战》书摘
书籍简介 名称:Go语言实战 作者: 威廉·肯尼迪 (William Kennedy) / 布赖恩·克特森 (Brian Ketelsen) / 埃里克·圣马丁 (Erik St.Martin) 内容 ...
- R入门<三>-R语言实战第4章基本数据管理摘要
入门书籍:R语言实战 进度:1-4章 摘要: 1)实用的包 forecast:用于做时间序列预测的,有auto.arima函数 RODBC:可以用来读取excel文件.但据说R对csv格式适应更加良好 ...
- R语言实战(三)基本图形与基本统计分析
本文对应<R语言实战>第6章:基本图形:第7章:基本统计分析 =============================================================== ...
- R语言实战(二)数据管理
本文对应<R语言实战>第4章:基本数据管理:第5章:高级数据管理 创建新变量 #建议采用transform()函数 mydata <- transform(mydata, sumx ...
- R语言实战(一)介绍、数据集与图形初阶
本文对应<R语言实战>前3章,因为里面大部分内容已经比较熟悉,所以在这里只是起一个索引的作用. 第1章 R语言介绍 获取帮助函数 help(), ? 查看函数帮助 exampl ...
- Swift语言实战晋级
Swift语言实战晋级基本信息作者: 老镇 丛书名: 爱上Swift出版社:人民邮电出版社ISBN:9787115378804上架时间:2014-12-26出版日期:2015 年1月开本:16开页码: ...
- swift语言实战晋级-第9章 游戏实战-跑酷熊猫-9-10 移除平台与视差滚动
9.9 移除场景之外的平台 用为平台是源源不断的产生的,如果不注意销毁,平台就将越积越多,虽然在游戏场景中看不到.几十个还看不出问题,那几万个呢?几百万个呢? 所以我们来看看怎么移除平台,那什么样的平 ...
- swift语言实战晋级-第9章 游戏实战-跑酷熊猫-7-8 移动平台的算法
在上个小节,我们完成了平台的产生.那么我们来实现一下让平台移动.平台的移动,我们只需要在平台工厂类中写好移动的方法,然后在GameScene类中统一控制就行了. 在GameScene类中,有个upda ...
- Swift语言实战晋级-第9章 游戏实战-跑酷熊猫-5-6 踩踏平台是怎么炼成的
在游戏中,有很多分来飞去的平台,这个平台长短不一.如果每种长度都去创建一张图片那是比较繁琐的事情.实际上,我们只用到3张图.分别是平台的,平台的中间部分,平台的右边.关键是平台的中间部分,两张中间部分 ...
随机推荐
- Linux如何从零开始搭建rsync服务器(centOS6)
Step1:检查rsync是否已经安装 rmp -qa rsync 如果没有安装的话,通过yum install rsync -y Step2:给rsync服务添加本地用户,用于管理本地目录. u ...
- 1.4socket服务器打印信息的四种不同方式()
方式一 socker 服务器 # -*- coding: utf-8 -*- import sys,os,multiprocessing from socket import * serverHost ...
- bootstrap table 分页显示问题
1.bootstrap-table客户端分页 客户端分页的数据源可以是后台服务器端传递过来(一次性获取,即获取所有你需要的数据),点击页码不再请求后台,利用页面缓存分页;cache : true, / ...
- 线程安全的集合类、CopyOnWrite机制介绍(转)
看过并发编程的书,这两种机制都有所了解,但不扎实其实.看到别人的博客描述的很精辟,于是转过来,感谢! 原文链接:https://blog.csdn.net/yen_csdn/article/detai ...
- js 数组去重的几种方式及原理
let arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,' ...
- leetcode第26题:删除排序数组的重复项
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成. 给定数组 ...
- ubuntu下用vagrant搭建集群环境
1.安装virtualbox 终端输入:sudo apt-get install virtualbox(事实从来都不是一番风顺的.......) 正在读取软件包列表... 完成 正在分析软件包的依赖关 ...
- Nginx web服务器
文件读取会使用到以下几个配置 1. sendfile 使用nginx作为静态资源服务时,通过配置sendfile可以有效提高文件读取效率,设置为on表示启动高效传输文件的模式.sendfile可以让N ...
- L1-028. 判断素数
本题的目标很简单,就是判断一个给定的正整数是否素数. 输入格式: 输入在第一行给出一个正整数N(<=10),随后N行,每行给出一个小于231的需要判断的正整数. 输出格式: 对每个需要判断的正整 ...
- asp.net 后台执行js
1. 用Response.Write方法 代码如下: Response.Write("<script type='text/javascript'>alert("XXX ...