一分鐘系列: Go 編程之用時定義

原文發佈於個人我的網站: GitDiG.com, 原文連接: 一分鐘系列: Go 編程之用時定義.

研究 Go 大神的開源庫,經常會有驚喜。以 Dave Cheney 的開源庫github.com/pkg/profile 爲例,其中有一句辣眼睛的寫法:git

// Start starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func Start(options ...func(*Profile)) interface {
    Stop()
} {
    //implemention codes
    ...
    return &prof 
}

咋一看,真是沒看懂。再仔細一看,其實只是在函數的返回結果時定義了一個匿名接口。爲方便記憶,不妨稱之爲用時定義, 即不是在返回前提早定義,而是在函數返回階段定義匿名接口。github

這麼作也的確有炫技的嫌疑,不過就算大神炫技,咱跟着看看學點有意思的東西也不錯。編程

import "github.com/pkg/profile"

func main() {
    defer profile.Start().Stop()
    ...
}

再看看該庫的使用指南,這種作法真的是優雅,經過一個匿名的接口定義限制並規範了對返回對象的使用。趕忙收藏!session

貼一個彩蛋,昨天 Dave Cheney 的Twitter:函數

package main

import (
    "fmt"
)

func main() {
   fmt.Println(0 > "0"[0])
}

答案有如下選擇:post

  1. 0
  2. true
  3. false
  4. 48

你們能夠選擇一下?答案過兩天評論裏給。網站

相關文章推薦:code

相關文章
相關標籤/搜索