linter warning: return value is ignored
19:54 07 May 2023

go-staticcheck issueing a warning: return value is ignored. This issue appears only inside a loop and specific condition. Let me clarify this:

for _, key := range []string{"my-foo", "bar", "baz"} {
  if strings.HasPrefix(key, "my") {
    fmt.Println(true)
  }
}

Until now, linter doesn't throw an issue. But when I remove fmt and use continue it throws issue:

for _, key := range []string{"my-foo", "bar", "baz"} {
  if strings.HasPrefix(key, "my") {
    continue
  }
}

HasPrefix is a pure function but its return value is ignored

The issue doesn't appear with strings.Contains(). It only appears with strings.HasPrefix() and only when use continue in the loop.


I also tried like this:

for _, key := range []string{"my-foo", "bar", "baz"} {
  hasMy := strings.HasPrefix(key, "my")
  if hasMy {
    continue
  }
}

Now, it lints 2 issues:

this value of hasMy is never used

HasPrefix is a pure function but its return value is ignored


Edit:

I was finding hard to ignore and thus pasting here for self reference. In case we need to ignore similar linter issue.

for _, key := range []string{"my-foo", "bar", "baz"} {
  //lint:ignore SA4017 // ignore this
  if strings.HasPrefix(key, "my") {
    continue
  }
}

Note: No space in between //lint.

go go-staticcheck