This was brought up in https://github.com/fyne-io/fyne/pull/1888 as a fix from deepsource. I thought it would be better to add this change to staticcheck instead.
The idea is to replace “checking an empty string by checking that length is 0” with instead checking “that the string is empty”. I don’t know if this is more of a subjective fix or if it has any performance implications. I guess it technically could be faster to do string == “” than len(string) == 0.
Before:
text := “hello”
if len(text) == 0 {
}
After:
text := “hello”
if text == “” {
}
I was recently thinking about this too. In general, the len form is annoying, but the one place where it seems clearer is when one wants to check the first rune byte if the string is not empty:
if len(s) != 0 && s[0] == '*' { /* … */ }
This nicely mirrors the way you would check any other slice.
I guess it technically could be faster to do string == “” than len(string) == 0
I would expect both forms to compile to the same code.
I do think this is too subjective, and prone to situations like the one outlined by Ainar. I don't think we would be able to catch _all_ special cases.
I vaguely remember discussing this kind of check with @dmitshur many years ago, maybe he's got some input, too.
As a picky aside, @ainar-g, you're checking the first byte, not the first rune ;)
I agree this is very subjective. I wrote a style entry about this at https://dmitri.shuralyov.com/idiomatic-go#empty-string-check, which suggests to prefer s == "" if you're checking if s is the empty string, but using len(s) is fine for other uses.
Unless you have a UI to make style suggestions that may apply 70% of the time and not apply 30% of the time in a way that doesn't frustrate users by making too many unhelpful suggestions, I don't see how it can be made into a check.
I am going to close this. I think both ways of checking for an empty string are fine, depending on the context (for example, I'd use len(s) when the next action is to slice the string). We can't make a general recommendation to use one or the other.
Most helpful comment
I would expect both forms to compile to the same code.
I do think this is too subjective, and prone to situations like the one outlined by Ainar. I don't think we would be able to catch _all_ special cases.
I vaguely remember discussing this kind of check with @dmitshur many years ago, maybe he's got some input, too.
As a picky aside, @ainar-g, you're checking the first byte, not the first rune ;)