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类型,请问这是为什么呢?

阅读 5.8k
4 个回答

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
}

好像是文件看错了,这是另一个 After

找到了,是在 sleep.go中的After()方法,返回一个 chan Time 类型

新手上路,请多包涵

func (t Time) After(u Time) bool,这个是time包里的Time结构体的一个After方法,func After(d Duration) <-chan Time才是time这个包提供的一个func,请阅读http://docscn.studygolang.com...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题