mirror of
https://github.com/teivah/100-go-mistakes.git
synced 2026-06-21 00:47:11 +08:00
Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
4e8d4da540
1 changed files with 23 additions and 0 deletions
|
|
@ -1726,6 +1726,29 @@ You should have a good reason to specify a channel size other than one for buffe
|
|||
|
||||
Remain cautious with functions accepting a `time.Duration`. Even though passing an integer is allowed, strive to use the time API to prevent any possible confusion.
|
||||
|
||||
Many common functions in the standard library accept a `time.Duration`, which is an alias for the `int64` type. However, one `time.Duration` unit represents one nanosecond, instead of one millisecond, as commonly seen in other programming languages. As a result, passing numeric types instead of using the `time.Duration` API can lead to unexpected behavior.
|
||||
|
||||
A developer with experience in other languages might assume that the following code creates a new `time.Ticker` that delivers ticks every second, given the value `1000`:
|
||||
|
||||
```go
|
||||
ticker := time.NewTicker(1000)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
// Do something
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
However, because 1,000 `time.Duration` units = 1,000 nanoseconds, ticks are delivered every 1,000 nanoseconds = 1 microsecond, not every second as assumed.
|
||||
|
||||
We should always use the `time.Duration` API to avoid confusion and unexpected behavior:
|
||||
```go
|
||||
ticker = time.NewTicker(time.Microsecond)
|
||||
// Or
|
||||
ticker = time.NewTicker(1000 * time.Nanosecond)
|
||||
```
|
||||
|
||||
[Source code :simple-github:](https://github.com/teivah/100-go-mistakes/tree/master/src/10-standard-lib/75-wrong-time-duration/main.go)
|
||||
|
||||
### `time.After` and memory leaks (#76)
|
||||
|
|
|
|||
Loading…
Reference in a new issue