英文:
How to write my own Sleep function using just time.After?
问题
我正在尝试编写一个等效于Go语言中的time.Sleep
函数的自定义睡眠函数,使用time.After
方法。
以下是代码。第一次尝试:
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
的睡眠函数,并且如果可能的话,什么时候使用通道?
英文:
I'm trying to write my own sleep function equivalent to time.Sleep
using time.After
in Go.
Here's the code. First attempt:
func Sleep(x int) {
msg := make(chan int)
msg := <- time.After(time.Second * x)
}
Second attempt:
func Sleep(x int) {
time.After(time.Second * x)
}
Both return errors, can someone explain to me how to write a sleep function equivalent to time.Sleep
using time.After
and if possible when do I use channel?
答案1
得分: 7
time.After()
返回一个通道。在指定的时间间隔之后,通道上会发送一个值。
所以只需从返回的通道接收一个值,接收操作将会阻塞,直到值被发送:
func Sleep(x int) {
<-time.After(time.Second * time.Duration(x))
}
你的错误:
在你的第一个示例中:
msg := <- time.After(time.Second * x)
msg
已经声明过了,所以不能使用短变量声明 :=
。此外,接收到的值将是time.Time
类型,所以你甚至不能将其赋值给 msg
。
在你的第二个示例中,你需要进行类型转换,因为 x
是 int
类型,而 time.Second
是 time.Duration
类型,而 time.After()
函数期望接收一个 time.Duration
类型的值。
英文:
time.After()
returns you a channel. And a value will be send on the channel after the specified duration.
So just receive a value from the returned channel, and the receive will block until the value is sent:
func Sleep(x int) {
<-time.After(time.Second * time.Duration(x))
}
Your errors:
In your first example:
msg := <- time.After(time.Second * x)
msg
is already declared, and so the Short variable declaration :=
cannot be used. Also the recieved value will be of type time.Time
, so you can't even assign it to msg
.
In your second example you need a type conversion as x
is of type int
and time.Second
is of type time.Duration
, and time.After()
expects a value of type time.Duration
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论