A deferred call is given an elapsed time, which is measured when defer runs rather than at the end

tx0/go:defer-evaluates-nowdefaultwarningbug

What it finds

defer log.Printf("took %v", time.Since(start)): the arguments of a deferred call are evaluated when the defer statement runs, not when the call does, so the duration is measured right at the start and is close to zero. Wrapping the call in a function literal, defer func() { ... }(), measures at the end.

Reported are arguments of a deferred call, at any depth outside function literals, that call time.Since or the method Sub on time.Now(), resolved through the imports.

From the rule's source, defer_evaluates_now.rs.

Example from the rule's tests
package p import (	"log"	"time") func f() {	start := time.Now()	defer log.Printf("took %v", time.Since(start))tx0 reports: time.Since(start) is evaluated when defer runs	defer observe(time.Now().Sub(start).Seconds())tx0 reports: time.Now().Sub(start) is evaluated when defer runs	defer func() { log.Printf("took %v", time.Since(start)) }()	defer observe(1)} func observe(float64) {}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:defer-evaluates-now" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:defer-evaluates-now] reason="..."

tx0 explain tx0/go:defer-evaluates-now shows the same in the terminal. Found a false positive? Report it.