Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

linter warning: return value is ignored

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading