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
}
}
有疑问加站长微信联系(非本文作者)