How to calculate duration without violating durationcheck?
A common requirement is to read a value from some where and use it to compose a duration, for example, read from json to get a value as seconds and save to a variable:
s := gjson.Get(js, "duration").Int()
usually we create a duration by multiply time.Second:
du := time.Second * time.Duration(s)
But this will trigger a durationcheck failure.
I understand why durationcheck is required, but I'm confused what's the elegant way to process this problem because a direct multiply from int to time.Duration is not allowed, would you give an example to show the me the solution?
Does durationcheck complain about that? It's a valid case and there's a passing test for it as well.
https://github.com/charithe/durationcheck/blob/c941235bd066b4626e062362331996f9d149f7ef/testdata/src/a/a.go#L48
I see what's going on here:
du := time.Duration(s)
timer := time.NewTicker(du * time.Second)
will be complained:
media/dmi/dmi_module.go:296:26: Multiplication of durations: `du * time.Second` (durationcheck)
timer := time.NewTicker(du * time.Second)
and this will NOT:
timer := time.NewTicker(time.Duration(s) * time.Second)
This is weird
I see. Durationcheck can detect inline casts to time.Duration but not ones that have been done elsewhere because it does not keep track of all the variables defined in the program. That's why you are seeing that warning. To the linter it looks like there are two durations being multiplied.
Unfortunately, tracking variables is quite complicated and this linter is a best-effort one meant to help you detect potentially wrong usage. If you're sure that the multiplication is valid, then I suggest using //nolint:durationcheck to disable the check for that line.
Great, thanks for your suggestion, it might be best option for me now.