golang相關知識

defer與panic

func中defer是隊列形式存儲的,panic執行後面的defer不加入隊列

package main

import (
    "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 main

import (
    "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 main

import (
    "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
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章