Skip to content

Commit

Permalink
Merge pull request #51 from jushutch/summarize-mistake-75
Browse files Browse the repository at this point in the history
Write summary for mistake 75
  • Loading branch information
teivah committed Oct 10, 2023
2 parents af8a2d0 + a4255e7 commit 64b636d
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 64b636d

Please sign in to comment.