defer和time
defer
go
// 跟在defer后的函数,我们一般称之为延迟函数
// 让函数或方法在当前函数执行完毕后但在在return或者panic之前执行。
//func main() {
// x := 10
// defer func() {
// x++
// //这里打印11
// fmt.Println("我后执行:", x)
// }()
// //这里打印10
// fmt.Println("我先执行:", x)
// return
//}
func main() {
x := 10
deferTest(1) // 1
defer func(x int) {
//打印10 因为x传参时,值为10
fmt.Println("我后执行:", x) // 4
}(x)
x++
fmt.Println("我先执行:", x) // 2
deferTest(2) //3 因为return 所以执行了
return
}
func deferTest(a int) {
//输出1
defer fmt.Println(a)
return
}
time
go
func main() {
//当前的时间
t1 := time.Now()
//格式化 这个是格式 2006-01-02 15:04:05
fmt.Println(t1.Format("2006-01-02 15:04:05")) //小口决,612345
t2 := time.Now()
//毫秒值
milli := t2.UnixMilli()
//秒值
second := t2.Unix()
fmt.Printf("毫秒值:%d, 秒值:%d \n", milli, second)
// 时间相加相减:
t3 := time.Now()
fmt.Println(t3.Format("2006-01-02 15:04:05"))
after20s := t3.Add(20 * time.Second)
fmt.Println(after20s.Format("2006-01-02 15:04:05"))
sub := after20s.Sub(t3)
fmt.Printf("相减时间:%v \n", sub)
// 休眠:
//阻塞当前的go程x时间,x<=0时立即 释放
time.Sleep(2 * time.Second)
fmt.Println("等2秒打印出来")
// 经过一段时间后返回
ch := make(chan struct{})
go wait1(ch)
select {
case <-ch:
fmt.Println("wait执行成功")
case <-time.After(2 * time.Second):
fmt.Println("wait等待时间已经超过2秒,超时了")
}
}
func wait1(ch chan struct{}) {
time.Sleep(3 * time.Second)
ch <- struct{}{}
}