Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to test for an empty string in Go?

Which method is best (most idomatic) for testing non-empty strings (in Go)?

if len(mystring) > 0 { } 

Or:

if mystring != "" { } 

Or something else?

like image 732
Richard Avatar asked Sep 03 '13 14:09

Richard


People also ask

How do you check if a string is empty in Go?

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.

Which function is used to check an empty string?

Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.

How do you test that a string str is the empty string?

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.

Can a string be null in Go?

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.


1 Answers

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.

like image 127
ANisus Avatar answered Oct 20 '22 09:10

ANisus