<p>Consider the following <a href="https://play.golang.org/p/eJooW02GEh" rel="nofollow">go playground</a></p>
<pre><code>package main
import (
"fmt"
"time"
)
func simulateEvent(name string, timeInSecs int32) {
// sleep for a while to simulate time consumed by event
fmt.Println("Started ", name, ": Should take", timeInSecs, "seconds.")
time.Sleep(time.Duration(timeInSecs) )
fmt.Println("Finished ", name)
}
func main() {
go simulateEvent("100m sprint", 10) //start 100m sprint, it should take 10 seconds
go simulateEvent("Long jump", 6) //start long jump, it should take 6 seconds
go simulateEvent("High jump", 3) //start high jump, it should take 3 seconds
//so that the program doesn't exit here, we make the program wait here for a while
time.Sleep(12 * 1e9)
}
</code></pre>
<p>In the main thread using <code>time.Sleep(12 * 1e9)</code> is fine.</p>
<p>While in the sub thread I have to explicitly use <code>time.Sleep(time.Duration(timeInSecs) )</code> or else the compiler will complain</p>
<p>This is confusing since the documentation explicitly says to use <code>Duration</code> type. </p>
<p>Can someone give some insight on this?</p>
<p>Thanks</p>
<hr/>**评论:**<br/><br/>Akkifokkusu: <pre><p>In <code>main</code>, <code>12 * 1e9</code> is an untyped constant, meaning it can be assigned to/used as any integer type without explicit conversion.</p>
<p>In <code>simulateEvent</code>, <code>timeInSecs</code> is explicitly type <code>int32</code>. Assigning or using as any other type requires conversion.</p>
<p>See <a href="https://blog.golang.org/constants" rel="nofollow">https://blog.golang.org/constants</a></p></pre>painakk: <pre><p>Ah, thanks for the source, that make alot of sense.</p></pre>010a: <pre><p>In addition to what <a href="/u/Akkifokkusu" rel="nofollow">/u/Akkifokkusu</a> says, which is correct, I will also point out that using <code>select {}</code> to make your main thread infinitely loop is probably superior to <code>time.Sleep</code> (and innumerably superior to <code>for {}</code>). </p></pre>painakk: <pre><p>Oh yeah select is definitely the idiomatic way, I was just experimenting around go func</p></pre>sethammons: <pre><p>I would add that you will be better off using <code>time.Sleep(300 * time.Millisecond)</code>. It works for the same reason <code>12 * 1e9</code> does, but is very readable. You can change that to <code>time.Second</code> or <code>time.Minute</code> or whatever. </p>
<p>I've heard that <code><-time.After(someDuration)</code> is better, though, I don't think it really matters. </p></pre>painakk: <pre><p>good idea, thanks</p></pre>
Why is the requirement of converting time.Sleep parameter to time.Duration type not consistent?
polaris · · 382 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传