golang - time.After()返回值问题

查看:388
本文介绍了golang - time.After()返回值问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

关于golang中time.After()的返回值是什么?

package main 
import(
    "fmt"
    "time"
)
func say(s string){
    for i := 0;i < 5;i++{
        fmt.Println(s)
    }
}
func main() {
    a := time.After(time.Second * 2)
    fmt.Printf("%T",a)
}

输出的结果为:

<-chan time.Time

上面的结果说明time.After()的返回值是一个 chan 类型。

但是我看了time.go的源码,包括github上面的go语言源代码(time.go),发现After()的源码如下:

// After reports whether the time instant t is after u.
func (t Time) After(u Time) bool {
    if t.wall&u.wall&hasMonotonic != 0 {
        return t.ext > u.ext
    }
    ts := t.sec()
    us := u.sec()
    return ts > us || ts == us && t.nsec() > u.nsec()
}

从源码中可以看出来,After()的返回值是一个bool类型,请问这是为什么呢?

解决方案

time/sleep.go

// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
    return NewTimer(d).C
}

这篇关于golang - time.After()返回值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆