藝多不壓身,學習一下最近蠻火的Go語言,整理一下筆記。相關Code和筆記也放到了Git上,傳送門。git
函數 -- 一等公民
與其餘主要編程語言的差別github
函數 可變參數及延遲運行編程
可變參數編程語言
func sum(ops ... int) int { s := 0 for _, op := range ops { s += op } return s }
延遲執行函數 defer 相似於Finnaly函數
func TestDefer(t *testing.T){ defer func() { /*這個內聯函數直到TestDefer執行完畢,返回前纔會執行。 一般用於清 理資源,釋放鎖等功能*/ t.Log("Clear resources") }() t.Log("Started") panic("Fatal error") //defer 仍會執行 //panic是Go中程序異常中斷,拋出致命錯誤 }
附上代碼:學習
package func_test import ( "testing" "math/rand" "time" "fmt" ) // 函數多個返回值 func returnMultiValues() (int, int) { return rand.Intn(10), rand.Intn(20) } func slowFun(op int) int{ time.Sleep(time.Second *1) fmt.Println("In SlowFun, the parameter is", op) return op } // 傳遞一個函數進來 func timeSpent(inner func(op int) int) func(op int) int { return func(n int) int { start := time.Now() ret := inner(n) fmt.Println("time spent:", time.Since(start).Seconds()) return ret } } func TestFn(t *testing.T) { // 函數多個返回值 a, b := returnMultiValues() t.Log(a, b) // 計算函數運行時間 tsSF := timeSpent(slowFun) t.Log(tsSF(10)) } func Sum (ops ... int) int { ret := 0 for _, s := range ops { ret += s } return ret } func TestVarParam(t *testing.T) { t.Log(Sum(1,2,3,4)) t.Log(Sum(5,6,7,8,9)) } func Clear() { fmt.Println("Clear resources in Clear function.") } func TestDefer(t *testing.T){ defer func() { //這個內聯函數直到TestDefer執行完畢,返回前纔會執行。 一般用於清理資源,釋放鎖等功能 defer Clear() t.Log("Clear resources") }() t.Log("Started") panic("Fatal error") //defer 仍會執行 //panic是Go中程序異常中斷,拋出致命錯誤 }