modified: 18.1.md

new file:   18.10.md
	new file:   18.11.md
	new file:   18.2.md
	new file:   18.3.md
	new file:   18.4.md
	modified:   18.5.md
	new file:   18.6.md
	new file:   18.7.md
	new file:   18.8.md
	new file:   18.9.md
	modified:   directory.md
This commit is contained in:
songleo
2016-01-03 13:53:23 +08:00
parent 7ea77a4738
commit 7c06912c30
12 changed files with 417 additions and 75 deletions

View File

@@ -32,13 +32,16 @@ for ix, ch := range str {
如何获取一个字符串的字符数:
最快速:`utf8.RuneCountInString(str)`
最快速:
```go
utf8.RuneCountInString(str)
```
`len([]int(str)) //TBD`
5如何连接字符串
最快速: `with a bytes.Buffer`(参考[章节7.2](07.2.md)
最快速:
`with a bytes.Buffer`(参考[章节7.2](07.2.md)
`Strings.Join()`(参考[章节4.7](04.7.md)

23
eBook/18.10.md Normal file
View File

@@ -0,0 +1,23 @@
# 18.10 其他
如何在程序出错时停止:
```go
if err != nil {
fmt.Printf(“Program stopping with error %v”, err)
os.Exit(1)
}
```
或者:
```go
if err != nil {
panic(“ERROR occurred: “ + err.Error())
}
```
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

19
eBook/18.11.md Normal file
View File

@@ -0,0 +1,19 @@
# 18.11 出于性能考虑的最佳实践和建议
1尽可能的使用:=去初始化声明一个变量(在函数内部);
2尽可能的使用字符代替字符串
3尽可能的使用切片代替数组
4尽可能的使用数组和切片代替映射详见 参考文献15
5如果只想获取切片中某项值不需要值的索引尽可能的使用for range去遍历切片这比必须去查询切片中的每个元素要快一些;
6当数组元素是稀疏的例如有很多0值或者空值使用映射会降低内存消耗
7初始化映射时指定其容量
8当定义一个方法时使用指针类型作为方法的接受者
9在代码中使用常量或者标志提取常亮的值
10尽可能在需要分配大量内存时使用缓存
11使用缓存模板参考15.7小节)。
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

46
eBook/18.2.md Normal file
View File

@@ -0,0 +1,46 @@
# 18.2 数组和切片
创建: `arr1 := new([len]type)`
`slice1 := make([]type, len)`
初始化:`arr1 := [...]type{i1, i2, i3, i4, i5}`
`arrKeyValue := [len]type{i1: val1, i2: val2}`
`var slice1 []type = arr1[start:end]`
1如何截断数组或者切片的最后一个元素
`line = line[:len(line)-1]`
2如何使用`for`或者`for-range`遍历一个数组(或者切片):
```go
for i:=0; i < len(arr); i++ {
= arr[i]
}
for ix, value := range arr {
}
```
3如何在一个二维数组或者切片arr2Dim中查找一个指定值V
```go
found := false
Found: for row := range arr2Dim {
for column := range arr2Dim[row] {
if arr2Dim[row][column] == V{
found = true
break Found
}
}
}
```
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

28
eBook/18.3.md Normal file
View File

@@ -0,0 +1,28 @@
# 18.3 映射
创建: `map1 := make(map[keytype]valuetype)`
初始化: `map1 := map[string]int{"one": 1, "two": 2}`
1如何使用`for`或者`for-range`遍历一个映射:
```go
for key, value := range map1 {
}
```
2如何在一个映射中检测键key1是否存在
`val1, isPresent = map1[key1]`
返回值: 键`key1`对应的值或者`0`, `true`或者`false`
3如何在映射中删除一个键
`delete(map1, key1)`
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

34
eBook/18.4.md Normal file
View File

@@ -0,0 +1,34 @@
# 18.4 结构体
创建:
```go
type struct1 struct {
field1 type1
field2 type2
}
ms := new(struct1)
```
初始化:
```go
ms := &struct1{10, 15.5, "Chris"}
```
当结构体的命名以大写字母开头时,该结构体在包外可见。
通常情况下为每个结构体定义一个构建函数并推荐使用构建函数初始化结构体参考例10.2
```go
ms := Newstruct1{10, 15.5, "Chris"}
func Newstruct1(n int, f float32, name string) *struct1 {
return &struct1{n, f, name}
}
```
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

View File

@@ -1,65 +1,36 @@
# 18.1 字符串
# 18.5 接口
1如何修改字符串中的一个字符
1如何检测一个值v是否实现了一个接口`Stringer`
```go
str:="hello"
c:=[]byte(s)
c[0]='c'
s2:= string(c) // s2 == "cello"
```
2如何获取字符串的子串
```go
substr := str[n:m]
```
3如何使用for或者for-range遍历一个字符串
```go
// gives only the bytes:
for i:=0; i < len(str); i++ {
= str[i]
}
// gives the Unicode characters:
for ix, ch := range str {
if v, ok := v.(Stringer); ok {
fmt.Printf("implements String(): %s\n", v.String())
}
```
4)如何获取一个字符串的字节数:`len(str)`
如何获取一个字符串的字符数:
最快速:`utf8.RuneCountInString(str)`
`len([]int(str)) //TBD`
5如何连接字符串
最快速: `with a bytes.Buffer`(参考[章节7.2](07.2.md)
`Strings.Join()`(参考[章节4.7](04.7.md)
`+=`
2)如何使用接口实现一个类型分类函数:
```go
str1 := "Hello "
str2 := "World!"
str1 += str2 //str1 == "Hello World!"
func classifier(items ...interface{}) {
for i, x := range items {
switch x.(type) {
case bool:
fmt.Printf("param #%d is a bool\n", i)
case float64:
fmt.Printf("param #%d is a float64\n", i)
case int, int64:
fmt.Printf("param #%d is an int\n", i)
case nil:
fmt.Printf("param #%d is nil\n", i)
case string:
fmt.Printf("param #%d is a string\n", i)
default:
fmt.Printf("param #%ds type is unknown\n", i)
}
}
}
```
6如何解析命令行参数使用`os`或者`flag`包
(参考[例12.4](examples/chapter_12/fileinput.go)
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)
## 链接
- [目录](directory.md)

23
eBook/18.6.md Normal file
View File

@@ -0,0 +1,23 @@
# 18.6 函数
如何使用内建函数recover停止panic过程参考13.3小节):
```go
func protect(g func()) {
defer func() {
log.Println("done")
// Println executes normally even if there is a panic
if x := recover(); x != nil {
log.Printf("run time panic: %v", x)
}
}()
log.Println("start")
g()
}
```
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

52
eBook/18.7.md Normal file
View File

@@ -0,0 +1,52 @@
# 18.7 文件
1如何打开一个文件并读取
```go
file, err := os.Open("input.dat")
if err != nil {
fmt.Printf("An error occurred on opening the inputfile\n" +
"Does the file exist?\n" +
"Have you got acces to it?\n")
return
}
defer file.Close()
iReader := bufio.NewReader(file)
for {
str, err := iReader.ReadString('\n')
if err != nil {
return // error or EOF
}
fmt.Printf("The input was: %s", str)
}
```
2如何通过切片读写文件
```go
func cat(f *file.File) {
const NBUF = 512
var buf [NBUF]byte
for {
switch nr, er := f.Read(buf[:]); true {
case nr < 0:
fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
f.String(), er.String())
os.Exit(1)
case nr == 0: // EOF
return
case nr > 0:
if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n",
f.String(), ew.String())
}
}
}
}
```
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

112
eBook/18.8.md Normal file
View File

@@ -0,0 +1,112 @@
# 18.8 协程goroutine与通道channel
出于性能考虑的建议:
实践经验表明,如果你使用并行性获得高于串行运算的效率:在协程内部已经完成的大部分工作,其开销比创建协程和协程间通信还高。
1 出于出于性能考虑建议使用带缓存的通道:
使用带缓存的通道很轻易成倍提高它的吞吐量某些场景其性能可以提高至10倍甚至更多。通过调整通道的容量你可以尝试着更进一步的优化其的性能。
2 限制一个通道的数据数量并将它们封装在成一个数组:
如果使用通道传递大量单独的数据那么通道将变成你的性能瓶颈。然而当将数据块打包封装成数组在接收端解压数据时性能可以提高至10倍。
创建:`ch := make(chan type, buf)`
1如何使用for或者for-range遍历一个通道
```go
for v := range ch {
// do something with v
}
```
2如何检测一个通道ch是否是关闭的
```go
//read channel until it closes or error-condition
for {
if input, open := <-ch; !open {
break
}
fmt.Printf(%s , input)
}
```
或者使用1自动检测。
3如何通过一个通道让主程序等待直到协程完成
(信号量模式):
```go
ch := make(chan int) // Allocate a channel.
// Start something in a goroutine; when it completes, signal on the channel.
go func() {
// doSomething
ch <- 1 // Send a signal; value does not matter.
}()
doSomethingElseForAWhile()
<-ch // Wait for goroutine to finish; discard sent value.
```
如果希望程序必须一直阻塞,在匿名函数中省略 `ch <- 1`即可。
4通道的工厂模板下面的函数是一个通道工厂启动一个匿名函数作为协程以生产通道
```go
func pump() chan int {
ch := make(chan int)
go func() {
for i := 0; ; i++ {
ch <- i
}
}()
return ch
}
```
5通道迭代器模板
6如何限制并发处理请求的数量参考14.11小节
7如何在多核CPU上实现并行计算参考14.13小节
(8)如何停止一个协程:`runtime.Goexit()`
9简单的超时模板
```go
timeout := make(chan bool, 1)
go func() {
time.Sleep(1e9) // one second
timeout <- true
}()
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}
```
10如何使用输入通道和输出通道代替锁
```go
func Worker(in, out chan *Task) {
for {
t := <-in
process(t)
out <- t
}
}
```
11如何在同步调用运行时间过长时将之丢弃参考14.5小节 第二个变体
12如何在通道中使用计时器和定时器参考14.5小节
13典型的服务器后端模型参考14.4小节
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

20
eBook/18.9.md Normal file
View File

@@ -0,0 +1,20 @@
# 18.9 网络和网页应用
## 18.9.1 模板:
制作、解析并是模块生效:
```go
var strTempl = template.Must(template.New(“TName”).Parse(strTemplateHTML))
```
在网页应用中使用HTML过滤器过滤HTML特殊字符
`{{html .}}` 或者通过一个字段 `FieldName {{ .FieldName |html }}`
使用缓存模板参考15.7小节)
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

View File

@@ -149,7 +149,18 @@
- 第16章常见的陷阱与错误
- 第17章模式
- 第18章出于性能考虑的实用代码片段
- 第18章[出于性能考虑的实用代码片段](18.0.md)
-18.1
-18.2
-18.3
-18.4
-18.5
-18.6
-18.7
-18.8
-18.9
-18.10
-18.11
- 第19章构建一个完整的应用程序
- 第20章Go 语言在 Google App Engine 的使用
- 第21章实际部署案例