如何用时间写自己的睡眠功能。之后? [英] How to write my own Sleep function using just time.After?

查看:191
本文介绍了如何用时间写自己的睡眠功能。之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Go中使用 time.After 编写自己的睡眠函数,该函数相当于 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)





$ b

这两个函数都返回错误,有人可以向我解释如何编写一个相当于 time.Sleep 使用 time.After 并且如果可能的话何时使用频道?

解决方案

时间。 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


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?

解决方案

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.

这篇关于如何用时间写自己的睡眠功能。之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆