A pointer is compared with nil after a field was already read or written through it

tx0/go:nil-check-after-userecommendedwarningbug

What it finds

``go name := cfg.Name if cfg == nil { return errNoConfig } ` If cfg` can be nil, which the check says it can, the first line already panicked before the check could help. The check belongs before the first use.

Both statements must be in the same block, the use first: a field selection p.f through the variable that is not a method call, in a statement that is not itself a branch. The later statement must be an if whose condition compares the variable with nil, and its init statement must not assign the variable. No statement in between may assign the variable, and none may be a branch, whose own checks could guard the use; and no earlier if of the block, or if around it, may compare the variable with nil already.

From the rule's source, nil_check_after_use.rs.

Example from the rule's tests
package p import "errors" type config struct{ Name string } func load(cfg *config) (string, error) {	name := cfg.Nametx0 reports: cfg is used here before it is checked for nil	if cfg == nil {		return "", errors.New("no config")	}	return name, nil} func fine(cfg *config) string {	if cfg == nil {		return ""	}	return cfg.Name} func reassigned(cfg *config) string {	n := cfg.Name	cfg = nil	if cfg == nil {		return n	}	return ""}
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 from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:nil-check-after-use" = "warning"

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:nil-check-after-use] reason="..."

tx0 explain tx0/go:nil-check-after-use shows the same in the terminal. Found a false positive? Report it.