更多個人筆記見:
github個人筆記倉庫
gitee 個人筆記倉庫
個人學習,學習過程中還會不斷補充~ (后續會更新在github上)
文章目錄
- Func 函數
- 函數棧概念
- 函數表示類型
- Anonymous func 匿名函數
- closure 閉包
- 基礎示例
- http利用閉包裹挾中間件
- 流程控制
- if else
- switch代碼
Func 函數
函數是一等公民!! 可以作為返回值,用作變量或者賦值等
函數棧概念
函數調用的時候消耗棧空間,因為調用完函數需要返回原來地方繼續執行 棧說明是后進先出的方式
同時每個協程都有一個棧,并且初始化大概2KB,可以擴容
函數表示類型
func visit (numbers []int,callback func(int)) {//func(int) represents it receives an interger but return nothingfor _,num := range numbers {callback(num)}}
callback 就是一個傳入 int 的函數
Anonymous func 匿名函數
示例: 就是看立即調用還是手動調用
package mainimport "fmt"func main() {func(){fmt.Println("Hello, world!")}() //立刻調用myfunc := func() {fmt.Println("Hello, myfunc!")}myfunc() //手動調用dosomething(func(){fmt.Println("Hello, dosomething!")})
}func dosomething(f func()) {f() //內部手動調用
}
closure 閉包
閉包可以修改之中的局部變量,在調用的時候同時故事保持之中的局部變量不變
基礎示例
package mainimport "fmt"func main(){nextInt:= intSeq()fmt.Println(nextInt())fmt.Println(nextInt())fmt.Println(nextInt())// 1 2 3newInts := intSeq()fmt.Println(newInts())//1//雖然 addr 不接受參數,但是它仍然可以訪問外部變量 sum。pos,neg := adder(),adder() //這里已經調用了 adder 函數for i :=0 ; i< 5; i++ {fmt.Println(pos(i),neg(-2*i),)}}//intSeq 函數返回另一個在 intSeq 函數體內定義的匿名函數。返回的函數使用閉包的方式 隱藏 變量 i。
func intSeq() func() int {i := 0return func() int {i++return i}// the func capture the "i"
}//sum
func adder() func(int) int {sum := 0return func(x int) int {sum += xreturn sum}}
(回調函數,函數式編程中常用)
http利用閉包裹挾中間件
設計到 gin 等 web 框架的概念
package mainimport ("fmt""net/http""time"
)func timed(f func(http.ResponseWriter, *http.Request)) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {start := time.Now()f(w, r) //執行原本的hello函數end := time.Now()fmt.Println("Time taken:", end.Sub(start)) //打印在控制臺}
}
func hello(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hello, World!")
}func main() {http.HandleFunc("/hello", timed(hello)) //訪問http://localhost:8080/hellohttp.ListenAndServe(":8080", nil)
}
流程控制
if else
注意格式就行
package mainimport "fmt"func main() {a := 1b := 2if a > b {fmt.Println("a > b")} else if a == b {fmt.Println("a = b")} else {fmt.Println("a < b")}
}
switch代碼
package mainimport "fmt"func main() {tag := "h"switch tag {case "h":fmt.Println("高")case "m":fmt.Println("中")case "l":fmt.Println("低")default:fmt.Println("未知")}
}