关于 Golang 你可能不知道的几件事

本文翻译自 https://talks.golang.org/2012/10things.slide

1. 匿名 struct

聚集全局变量 Grouped globals

1
2
3
4
5
6
var config struct {
APIKey string
OAuthConfig oauth.Config
}

config.APIKey = "BADC0C0A"

模板数据 Template data

1
2
3
4
5
6
7
8
data := struct {
Title string
Users []*User
}{
title,
users,
}
err := tmpl.Execute(w, data)

组织测试数据 Test tables

1
2
3
4
5
6
7
8
9
10
var indexRuneTests = []struct {
s string
rune rune
out int
}{
{"a A x", 'A', 2},
{"some_text=some_value", '=', 9},
{"☺a", 'a', 3},
{"a☻☺b", '☺', 4},
}

嵌入式 lock Embeded lock

1
2
3
4
5
6
7
8
var hits struct {
sync.Mutex
n int
}

hits.Lock()
hits.n++
hits.Unlock()

2. 嵌套 struct

嵌套 JSON 解析 Decoding deeply nested JSON data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{"data": {"children": [
{"data": {
"title": "The Go homepage",
"url": "http://golang.org/"
}},
...
]}}

type Item struct {
Title string
URL string
}

type Response struct {
Data struct {
Children []struct {
Data Item
}
}
}

3. 命令行 doc

1
2
3
4
5
// Mutex 文档
% godoc sync Mutex

// 显示私有变量
% godoc -src sync Mutex

4. mock 文件系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

var fs fileSystem = osFS{}

type fileSystem interface {
Open(name string) (file, error)
Stat(name string) (os.FileInfo, error)
}

type file interface {
io.Closer
io.Reader
io.ReaderAt
io.Seeker
Stat() (os.FileInfo, error)
}

// osFS implements fileSystem using the local disk.
type osFS struct{}

func (osFS) Open(name string) (file, error) { return os.Open(name) }
func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }

5. 方法表达式

1
2
3
4
type T struct {}
func (T) Foo(s string) { println(s) }

var fn func(T, string) = T.Foo
1
2
3
4
5
6
7
8
9
10
11
12
13
func (c *Cmd) stdin() (f *os.File, err error)
func (c *Cmd) stdout() (f *os.File, err error)
func (c *Cmd) stderr() (f *os.File, err error)
type F func(*Cmd) (*os.File, error)
for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
fd, err := setupFd(c)
if err != nil {
c.closeDescriptors(c.closeAfterStart)
c.closeDescriptors(c.closeAfterWait)
return err
}
c.childFiles = append(c.childFiles, fd)
}

6. 同一个 channel 发送和接受

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

package main

import "fmt"

var battle = make(chan string)

func warrior(name string, done chan struct{}) {
select {
case opponent := <-battle:
fmt.Printf("%s beat %s\n", name, opponent)
case battle <- name:
// I lost :-(
}
done <- struct{}{}
}

func main() {
done := make(chan struct{})
langs := []string{"Go", "C", "C++", "Java", "Perl", "Python"}
for _, l := range langs { go warrior(l, done) }
for _ = range langs { <-done }
}

7. 使用 close channel 完成广播

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func waiter(i int, block, done chan struct{}) {
time.Sleep(time.Duration(rand.Intn(3000)) * time.Millisecond)
fmt.Println(i, "waiting...")
<-block
fmt.Println(i, "done!")
done <- struct{}{}
}

func main() {
block, done := make(chan struct{}), make(chan struct{})
for i := 0; i < 4; i++ {
go waiter(i, block, done)
}
time.Sleep(5 * time.Second)
close(block)
for i := 0; i < 4; i++ {
<-done
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

func worker(i int, ch chan Work, quit chan struct{}) {
var quitting bool
for {
select {
case w := <-ch:
if quitting {
w.Refuse(); fmt.Println("worker", i, "refused", w)
break
}
w.Do(); fmt.Println("worker", i, "processed", w)
case <-quit:
fmt.Println("worker", i, "quitting")
quitting = true
}
}
}

func main() {
ch, quit := make(chan Work), make(chan struct{})
go makeWork(ch)
for i := 0; i < 4; i++ { go worker(i, ch, quit) }
time.Sleep(5 * time.Second)
close(quit)
time.Sleep(2 * time.Second)
}

8. select 中的 nil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

func worker(i int, ch chan Work, quit chan struct{}) {
for {
select {
case w := <-ch:
if quit == nil {
w.Refuse(); fmt.Println("worker", i, "refused", w)
break
}
w.Do(); fmt.Println("worker", i, "processed", w)
case <-quit:
fmt.Println("worker", i, "quitting")
quit = nil
}
}
}

func main() {
ch, quit := make(chan Work), make(chan struct{})
go makeWork(ch)
for i := 0; i < 4; i++ { go worker(i, ch, quit) }
time.Sleep(5 * time.Second)
close(quit)
time.Sleep(2 * time.Second)
}
三月沙 wechat
扫描关注 wecatch 的公众号