1. 匿名结构体

  • 全局组合
1
2
3
4
5
var config struct {//定义一个用于全局配置结构体  APIKey string  OAuthConfig oauth.Config } config.APIKey = "BADC0C0A" 

  • 数据模板
5
6
7
8
data := //匿名结构体的定义  Title Users []*User }{//同时初始化  title,  users, } err := tmpl.Execute(w, data) 

(比map[string]interface{}消耗更小和更安全)

  • 测试表(用作测试数据构造)
8
9
10
indexRuneTests = []struct {  s rune rune  out int }{  {"a A x", 'A', 2},  {"some_text=some_value", '=',152)!important">9},152)!important">"☺a", 'a',152)!important">3},152)!important">"a☻☺b", '☺',152)!important">4}, } 

  • 嵌套加锁
7
hits sync.Mutex  n int } hits.Lock() n++//十对“n”的操作是安全的 Unlock() 

2. 嵌套结构体

  • 反序列化深层嵌套的json
10
11
12
13
14
15
16
17
18
{"data": {"children": [  {"data": {  "title": "The Go homepage",  "url": "http://golang.org/"  }},  ... ]}} type Item URL string } Response Data Children []Data Item  }  } } 

3. godoc命令,输出package的文档注释

1
% godoc sync Mutex 

输出

18
19
20
21
22
23
24
PACKAGE  package sync  import "sync"  TYPES  Mutex struct {  // contains filtered or unexported fields }  A Mutex is a mutual exclusion lock. Mutexes can be created as part of  other structures; the zero value for an unlocked mutex.  func (m *Mutex) Lock()  Lock locks m. If lock already in use,210)!important">calling goroutine  blocks until mutex available.  Unlock()  Unlock unlocks It run-time error if m not locked on entry to  Unlock.   associated with particular goroutine. is  allowed one goroutine to and then arrange another  unlock it. 

4. godoc -src 命令

1
% godoc -src sync Mutex 

输出

7
// A Mutex is a mutual exclusion lock. // Mutexes can be created as part of other structures; // the zero value for a Mutex is an unlocked mutex. state int32  sema uint32 } 

未导出的元素也将显示!

5. 获取指定域名下的包

1
go get camlistore.org/pkg/netutil 

go help remote可查看更详细的信息.

6. 模拟一个文件系统

获取到的包里,代码访问了文件系统,但是测试时不希望真正访问磁盘

20
fs fileSystem = osFS{}  fileSystem interface {  Open(name string) (file,210)!important">error)  Stat(os.FileInfo,210)!important">error) }  file io.Closer  Reader  ReaderAt  Seeker  Stat() (error) }  // osFS 实现接口filesystem,并访问本地磁盘. osFS struct{}  osFS) error) { return name) } name) } 

7. 方法表达式

4
T struct {} T) Foo(string) { println(s) }  fn func(T, string) = T.Foo//将方法赋值给一个方法变量 

os/exec中的实际例子:

13
c *Cmd) stdin() (f *File,210)!important">err error) stdout() (stderr() (F func(*Cmd) (*_,210)!important">setupFd := range []F{(*Cmd).stdin, (*stdout,210)!important">stderr} {  fd,210)!important">setupFd(c)  err != nil {  c.closeDescriptors(closeAfterStart)  closeAfterWait)  err  }  childFiles = append(childFiles,210)!important">fd) } 

8. 使用统一个Channel发送和接收消息

22
main  "fmt"  battle = make(chan string)  func warrior(string,210)!important">done chan struct{}) {  select {  case opponent := <-battle:  fmt.Printf("%s beat %s\n",210)!important">name,210)!important">opponent)  battle <- name:  // I lost :-(  }  done <- struct{}{} }  main() {  done := struct{})  langs := []string{"Go", "C",152)!important">"C++",152)!important">"Java",152)!important">"Perl",152)!important">"Python"}  l := range langs { go l,210)!important">done) }  _ = langs { <-done } } 

9. 使用channel的close发送广播

19
waiter(i int,210)!important">block,22)!important">struct{}) {  time.Sleep(Duration(rand.Intn(3000)) * Millisecond)  Println(i,152)!important">"waiting...")  <-block  "done!")  struct{}),22)!important">struct{})  i := 0; i < 4; i++ {  done)  }  Sleep(5 * Second)  close(block)  i++ {  <-done  } } 

另外一个例子

24
worker(ch chan Work,210)!important">quit quitting bool  for {  w := <-ch:  quitting {  w.Refuse(); Println("worker",152)!important">"refused",210)!important">w)  break  }  Do(); "processed",22)!important">case <-quit:  "quitting")  quitting = true  }  } } ch,210)!important">quit := Work),210)!important">makeWork(ch)  i++ { quit) }  quit)  2 * Second) } 

10. select中使用空channel

quit == quit = nil } } } Second) }