linter warning: return value is ignored

854 Views Asked by At

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.

1

There are 1 best solutions below

0
Zac Anger On BEST ANSWER

Your continue is just running back through the loop, and there's no other code depending on the result of the HasPrefix (a bool), so in effect you're just wasting that call. A pure function is one that performs no side effects, so the linter knows that in this case that conditional could be removed entirely and wouldn't make any difference.

If you add an else after that if statement, you can see the lint warning go away (on my machine the error message is slightly different, but that could be a different version of staticcheck).

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

Or if you add something else inside the check as in your first version:

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

And the same applies to your second version using a variable to store the result of the HasPrefix.