In Go, check if a string is empty by comparing it directly to an empty string literal ("") using the equality operator. You can also check the length with len(s) == 0, but the direct comparison is generally preferred for readability.
Here are the two most common patterns:
package main
import "fmt"
func main() {
s := ""
// Method 1: Direct comparison (Recommended)
if s == "" {
fmt.Println("String is empty")
}
// Method 2: Length check
if len(s) == 0 {
fmt.Println("String length is zero")
}
}
A common mistake is trying to use nil to check for an empty string. Unlike slices, maps, or pointers, strings are value types that cannot be nil. A string variable is always initialized to "" if not explicitly set, so s == nil will cause a compile-time error.
// This will fail to compile:
// if s == nil { ... }
// Correct approach for optional strings (using pointers):
var ptr *string = nil
if ptr == nil || *ptr == "" {
// Handle nil or empty
}
When dealing with whitespace-only strings (e.g., " "), the standard equality check returns false because the string contains characters. Use strings.TrimSpace() if you need to treat whitespace-only strings as empty:
import "strings"
s := " "
if strings.TrimSpace(s) == "" {
fmt.Println("String contains only whitespace")
}
For performance-critical loops where you are checking the same string repeatedly, the compiler optimizes s == "" and len(s) == 0 identically, so choose based on code clarity. The direct comparison s == "" is the idiomatic Go approach and is immediately understandable to any Go developer reading your code.