mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 05:33:04 +08:00
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:
@@ -32,13 +32,16 @@ for ix, ch := range str {
|
|||||||
|
|
||||||
如何获取一个字符串的字符数:
|
如何获取一个字符串的字符数:
|
||||||
|
|
||||||
最快速:`utf8.RuneCountInString(str)`
|
最快速:
|
||||||
|
```go
|
||||||
|
utf8.RuneCountInString(str)
|
||||||
|
```
|
||||||
`len([]int(str)) //TBD`
|
`len([]int(str)) //TBD`
|
||||||
|
|
||||||
(5)如何连接字符串:
|
(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))
|
`Strings.Join()`(参考[章节4.7](04.7.md))
|
||||||
|
|
||||||
|
23
eBook/18.10.md
Normal file
23
eBook/18.10.md
Normal 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
19
eBook/18.11.md
Normal 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
46
eBook/18.2.md
Normal 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
28
eBook/18.3.md
Normal 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
34
eBook/18.4.md
Normal 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)
|
@@ -1,64 +1,35 @@
|
|||||||
# 18.1 字符串
|
# 18.5 接口
|
||||||
|
|
||||||
(1)如何修改字符串中的一个字符:
|
(1)如何检测一个值v是否实现了一个接口`Stringer`:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
str:="hello"
|
if v, ok := v.(Stringer); ok {
|
||||||
c:=[]byte(s)
|
fmt.Printf("implements String(): %s\n", v.String())
|
||||||
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 {
|
|
||||||
…
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
(4)如何获取一个字符串的字节数:`len(str)`
|
(2)如何使用接口实现一个类型分类函数:
|
||||||
|
|
||||||
如何获取一个字符串的字符数:
|
```go
|
||||||
|
func classifier(items ...interface{}) {
|
||||||
最快速:`utf8.RuneCountInString(str)`
|
for i, x := range items {
|
||||||
|
switch x.(type) {
|
||||||
`len([]int(str)) //TBD`
|
case bool:
|
||||||
|
fmt.Printf("param #%d is a bool\n", i)
|
||||||
(5)如何连接字符串:
|
case float64:
|
||||||
|
fmt.Printf("param #%d is a float64\n", i)
|
||||||
最快速: `with a bytes.Buffer`(参考[章节7.2](07.2.md))
|
case int, int64:
|
||||||
|
fmt.Printf("param #%d is an int\n", i)
|
||||||
`Strings.Join()`(参考[章节4.7](04.7.md))
|
case nil:
|
||||||
|
fmt.Printf("param #%d is nil\n", i)
|
||||||
`+=`
|
case string:
|
||||||
|
fmt.Printf("param #%d is a string\n", i)
|
||||||
```go
|
default:
|
||||||
str1 := "Hello "
|
fmt.Printf("param #%d’s type is unknown\n", i)
|
||||||
str2 := "World!"
|
}
|
||||||
str1 += str2 //str1 == "Hello World!"
|
}
|
||||||
```
|
}
|
||||||
|
```
|
||||||
(6)如何解析命令行参数:使用`os`或者`flag`包
|
|
||||||
|
|
||||||
(参考[例12.4](examples/chapter_12/fileinput.go))
|
|
||||||
|
|
||||||
## 链接
|
|
||||||
|
|
||||||
- [目录](directory.md)
|
|
||||||
- 上一章:[运算符模板和接口](17.4.md)
|
|
||||||
- 下一节:[字符串](18.1.md)
|
|
||||||
|
|
||||||
## 链接
|
## 链接
|
||||||
|
|
||||||
|
23
eBook/18.6.md
Normal file
23
eBook/18.6.md
Normal 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
52
eBook/18.7.md
Normal 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
112
eBook/18.8.md
Normal 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
20
eBook/18.9.md
Normal 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)
|
@@ -149,7 +149,18 @@
|
|||||||
|
|
||||||
- 第16章:常见的陷阱与错误
|
- 第16章:常见的陷阱与错误
|
||||||
- 第17章:模式
|
- 第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章:构建一个完整的应用程序
|
- 第19章:构建一个完整的应用程序
|
||||||
- 第20章:Go 语言在 Google App Engine 的使用
|
- 第20章:Go 语言在 Google App Engine 的使用
|
||||||
- 第21章:实际部署案例
|
- 第21章:实际部署案例
|
||||||
|
Reference in New Issue
Block a user