Which method is best (most idomatic) for testing non-empty strings (in Go)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
Or something else?
To check if a given string is empty or not, we can use the built-in len() function in Go language. or we can use the str == "" to check if a string is empty.
Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.
Empty strings contain zero characters and display as double quotes with nothing between them ( "" ). You can determine if a string is an empty string using the == operator. The empty string is a substring of every other string. Therefore, functions such as contains always find the empty string within other strings.
Because many languages conflate these two things, programmers are used to having to check if a string is null before using it. Go doesn't do this. A string cannot be nil, because the data structure in go doesn't allow it.
Both styles are used within the Go's standard libraries.
if len(s) > 0 { ... }
can be found in the strconv
package: http://golang.org/src/pkg/strconv/atoi.go
if s != "" { ... }
can be found in the encoding/json
package: http://golang.org/src/pkg/encoding/json/encode.go
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With