作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在尝试使用 Go 中的 time.After
编写自己的 sleep 函数,等同于 time.Sleep
。
这是代码。第一次尝试:
func Sleep(x int) {
msg := make(chan int)
msg := <- time.After(time.Second * x)
}
第二次尝试:
func Sleep(x int) {
time.After(time.Second * x)
}
两者都返回错误,有人可以向我解释如何使用 time.After
编写等同于 time.Sleep
的 sleep 函数吗?如果可能的话,我什么时候使用 channel ?
最佳答案
time.After()
返回给你一个 channel 。在指定的持续时间后,将在 channel 上发送一个值。
所以只需从返回的 channel 接收一个值,接收将阻塞直到发送该值:
func Sleep(x int) {
<-time.After(time.Second * time.Duration(x))
}
您的错误:
在你的第一个例子中:
msg := <- time.After(time.Second * x)
msg
已经声明,因此 Short variable declaration :=
不能使用。接收到的值也将是 time.Time
类型, 所以你甚至不能将它分配给 msg
。
在你的第二个例子中你需要一个类型 conversion因为 x
是 int
类型,time.Second
是 time.Duration
类型,并且 time.After()
需要一个 time.Duration
类型的值。
关于time - 如何仅使用 time.After 编写我自己的 Sleep 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942163/
我是一名优秀的程序员,十分优秀!