time.After()返回值问题
时间:2023-02-16
浏览:298
作者:佚名
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《time.After()返回值问题》,主要介绍了go,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
问题内容
关于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
}今天带大家了解了go的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
