patterngoCritical
What is the best way to test for an empty string in Go?
Viewed 0 times
emptythebestforwaystringwhattest
Problem
Which method is best (most idomatic) for testing non-empty strings (in Go)?
Or:
Or something else?
if len(mystring) > 0 { }Or:
if mystring != "" { }Or something else?
Solution
Both styles are used within the Go's standard libraries.
can be found in the
can be found in the
Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.
Russ Cox writes in a golang-nuts thread:
The one that makes the code clear.
If I'm about to look at element x I typically write
len(s) > x, even for x == 0, but if I care about
"is it this specific string" I tend to write s == "".
It's reasonable to assume that a mature compiler will compile
len(s) == 0 and s == "" into the same, efficient code.
...
Make the code clear.
As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.
if len(s) > 0 { ... }can be found in the
strconv package: http://golang.org/src/pkg/strconv/atoi.goif s != "" { ... }can be found in the
encoding/json package: http://golang.org/src/pkg/encoding/json/encode.goBoth are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.
Russ Cox writes in a golang-nuts thread:
The one that makes the code clear.
If I'm about to look at element x I typically write
len(s) > x, even for x == 0, but if I care about
"is it this specific string" I tend to write s == "".
It's reasonable to assume that a mature compiler will compile
len(s) == 0 and s == "" into the same, efficient code.
...
Make the code clear.
As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.
Code Snippets
if len(s) > 0 { ... }if s != "" { ... }Context
Stack Overflow Q#18594330, score: 736
Revisions (0)
No revisions yet.