Go語言 你可能不知道的十個技巧

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

1、匿名結構體

全域群組合

var config struct {// 定義一個用於全域配置結構體    APIKey      string    OAuthConfig oauth.Config}config.APIKey = "BADC0C0A"

資料範本

data := struct {//匿名結構體的定義  Title string  Users []*User}{//同時初始化  title,  users,}err := tmpl.Execute(w, data)

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

測試表(用作測試資料構造)

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},}

嵌套加鎖

var hits struct {  sync.Mutex  n int}hits.Lock()hits.n++//十對“n”的操作是安全的hits.Unlock()

2、嵌套結構體

還原序列化深層嵌套的json

{"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、godoc命令,輸出package的文檔注釋

% godoc sync Mutex

輸出

PACKAGEpackage sync    import "sync"TYPEStype 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 a Mutex is an unlocked mutex.func (m *Mutex) Lock()    Lock locks m. If the lock is already in use, the calling goroutine    blocks until the mutex is available.func (m *Mutex) Unlock()    Unlock unlocks m. It is a run-time error if m is not locked on entry to    Unlock.    A locked Mutex is not associated with a particular goroutine. It is    allowed for one goroutine to lock a Mutex and then arrange for another    goroutine to unlock it.

4、godoc -src 命令

% godoc -src sync Mutex

輸出

// 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.type Mutex struct {    state int32    sema  uint32}

未匯出的元素也將顯示!

5、擷取指定網域名稱下的包

go get camlistore.org/pkg/netutilgo help remote 可查看更詳細的資訊.

6、類比一個檔案系統

擷取到的包裡,代碼訪問了檔案系統,但是測試時不希望真正訪問磁碟

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 實現介面filesystem,並訪問本地磁碟.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) }

7、方法運算式

type T struct {}func (T) Foo(s string) { println(s) }var fn func(T, string) = T.Foo//將方法賦值給一個方法變數

os/exec中的實際例子:

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)}

8、使用統一個Channel發送和接收訊息

package mainimport "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 }}

9、使用channel的close發送廣播

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    }}

另外一個例子

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)}

10、select中使用空channel

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)}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.