This is a creation in Article, where the information may have evolved or changed.
Defer and panic
In func, defer is stored as a queue, panic does not join the queue after defer execution
package mainimport ( "fmt")func main() { defer_call()}func defer_call() { defer func() { fmt.Println("打印前") }() defer func() { fmt.Println("打印中") }() defer func() { fmt.Println("打印后") }() panic("触发异常")}
Range Reuse Address
Range Loop, the address is reused, that is, for _, Stu: = stu in range Stus always at the same address
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 }}
The case condition in select is random.
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) }}
The defer's anonymous function parameter is the copy address (if the pointer is the value of the last pointer), and the function inside the function is given precedence in the main function body.
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 is to append data to the back.
func main() { s := make([]int, 5) s = append(s, 1, 2, 3) fmt.Println(s) // 输出 0 0 0 0 0 1 2 3}
The interface interface does not pass the object type corresponding to the different set of methods, thus affecting the objects implemented by the 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{}}
When the class call of the interface interface is implemented, a copy of the new data is actually used (the address is not the same)
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")//Output when BBB Live () is actually var Stu *student var p people p=stu}}