How to write my own Sleep function using just time.After?

huangapple go评论78阅读模式
英文:

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 := &lt;- 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

在你的第二个示例中,你需要进行类型转换,因为 xint 类型,而 time.Secondtime.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) {
	&lt;-time.After(time.Second * time.Duration(x))
}

Your errors:

In your first example:

msg := &lt;- 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.

huangapple
  • 本文由 发表于 2015年8月11日 20:44:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/31942163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定