原文發佈於我的個人網站: GitDiG.com, 原文鏈接: 一分鐘系列: Go 編程之用時定義.
研究 Go 大神的開源庫,常常會有驚喜。以 Dave Cheney 的開源庫github.com/pkg/profile 爲例,其中有一句辣眼睛的寫法:
// 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
}
咋一看,真是沒看懂。再仔細一看,其實只是在函數的返回結果時定義了一個匿名接口。爲方便記憶,不妨稱之爲用時定義, 即不是在返回前提前定義,而是在函數返回階段定義匿名接口。
這麼做也的確有炫技的嫌疑,不過就算大神炫技,咱跟着看看學點有意思的東西也不錯。
import "github.com/pkg/profile"
func main() {
defer profile.Start().Stop()
...
}
再看看該庫的使用指南,這種做法真的是優雅,通過一個匿名的接口定義限制並規範了對返回對象的使用。趕緊收藏!
貼一個彩蛋,昨天 Dave Cheney 的Twitter:
package main
import (
"fmt"
)
func main() {
fmt.Println(0 > "0"[0])
}
答案有以下選擇:
- 0
- true
- false
- 48
大家可以選擇一下?答案過兩天評論裏給。
相關文章推薦: