這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
defer與panic
func中defer是隊列形式儲存的,panic執行後面的defer不排入佇列
package mainimport ( "fmt")func main() { defer_call()}func defer_call() { defer func() { fmt.Println("列印前") }() defer func() { fmt.Println("列印中") }() defer func() { fmt.Println("列印後") }() panic("觸發異常")}
range 重用地址
range 迴圈,會重用地址,也就是說,for _, stu := range stus 中的 stu 總是在同一個地址
type student struct { Name string Age int}func pase_student() { m := make(map[string]*student) stus := []student{ {Name: "zhou", Age: 24}, {Name: "li", Age: 23}, {Name: "wang", Age: 22}, } for _, stu := range stus { m[stu.Name] = &stu }}
select裡面的case條件是隨機性的
func main() { runtime.GOMAXPROCS(1) int_chan := make(chan int, 1) string_chan := make(chan string, 1) int_chan <- 1 string_chan <- "hello" select { case value := <-int_chan: fmt.Println(value) case value := <-string_chan: panic(value) }}
defer的匿名函數參數是拷貝地址的(如果是指標就是最後指標的值),而函數裡面的函數是優先在main函數體中執行的
func calc(index string, a, b int) int { ret := a + b fmt.Println(index, a, b, ret) return ret}func main() { a := 1 b := 2 defer calc("1", a, calc("10", a, b)) a = 0 defer calc("2", a, calc("20", a, b)) b = 1}
append 是往後面追加資料
func main() { s := make([]int, 5) s = append(s, 1, 2, 3) fmt.Println(s) // 輸出 0 0 0 0 0 1 2 3}
interface介面 不通的物件類型對應了不同的方法集,從而影響interface介面實現的對象
Methods Receivers Values-----------------------------------------------(t T) T and *T(t *T) *T
package mainimport ( "fmt")type People interface { Speak(string) string}type Stduent struct{}func (stu *Stduent) Speak(think string) (talk string) { if think == "bitch" { talk = "You are a good boy" } else { talk = "hi" } return}func main() { var peo People = Stduent{} think := "bitch" fmt.Println(peo.Speak(think)) //指標類型的receiver 方法實現介面時,只有指標類型的對象實現了該介面 需要改成var peo People = &Stduent{}}
實現了interface介面的類調用的時候其實已經拷貝了一份新的資料在使用了(地址不一樣)
package mainimport ( "fmt")type People interface { Show()}type Student struct{}func (stu *Student) Show() {}func live() People { var stu *Student return stu}func main() { if live() == nil { fmt.Println("AAAAAAA") } else { fmt.Println("BBBBBBB") //輸出的時BBB live() 實際上是 var stu *Student var p People p=stu }}