Question
In Go, what is the most idiomatic way to test whether a string is non-empty?
For example, is this preferred:
if len(myString) > 0 {
// string is not empty
}
Or is this better:
if myString != "" {
// string is not empty
}
Or is there another recommended approach?
Short Answer
By the end of this page, you will understand the idiomatic way to check whether a string is empty or non-empty in Go, when myString != "" and len(myString) > 0 are both valid, and how developers usually choose between them in real code.
Concept
In Go, the usual way to check whether a string is empty is to compare it directly with the empty string:
if myString != "" {
// non-empty
}
To check whether it is empty:
if myString == "" {
// empty
}
This is generally considered the most idiomatic approach because it expresses the intent clearly: you are checking whether the string equals the empty string.
You can also write:
if len(myString) > 0 {
// non-empty
}
This is valid and works correctly. In practice, both forms are efficient for ordinary use. The main difference is readability and intent:
myString != ""says compare with empty stringlen(myString) > 0says measure length and compare
When the goal is specifically to test emptiness, direct comparison is usually clearer.
This matters in real programming because empty-string checks appear everywhere:
- validating input
- checking config values
- skipping missing fields
- handling optional query parameters
- rejecting invalid API data
Using the clearest form makes code easier to read and maintain.
Mental Model
Think of a string as a label on a box.
myString == ""asks: Is the label blank?len(myString) > 0asks: Does the label contain at least one character?
Both questions lead to the same answer for emptiness, but the first one is more direct when blankness is exactly what you want to know.
So if your real question is "Is this string empty?", compare it to "".
If your real question is "How many characters are in this string?", use len(...).
Syntax and Examples
Basic syntax
Check for an empty string:
if myString == "" {
fmt.Println("empty")
}
Check for a non-empty string:
if myString != "" {
fmt.Println("not empty")
}
You can also use len:
if len(myString) > 0 {
fmt.Println("not empty")
}
Example
package main
import "fmt"
func main() {
name := "Go"
empty := ""
if name != "" {
fmt.Println("name has a value")
}
if empty == "" {
fmt.Println("empty is blank")
}
}
Why this is beginner-friendly
Step by Step Execution
Consider this example:
package main
import "fmt"
func main() {
s := "hello"
if s != "" {
fmt.Println("non-empty")
}
}
Step by step:
-
s := "hello"- A string variable named
sis created. - Its value is
"hello".
- A string variable named
-
if s != ""- Go compares
swith the empty string. "hello" != ""istrue.
- Go compares
-
fmt.Println("non-empty")- Because the condition is true, this line runs.
- Output:
non-empty
Now compare with an empty string:
Real World Use Cases
Input validation
if username == "" {
return errors.New("username is required")
}
Configuration values
if apiKey == "" {
log.Fatal("API key is missing")
}
Query parameters in web handlers
search := r.URL.Query().Get("q")
if search != "" {
fmt.Println("run search")
}
Optional fields in JSON or forms
if user.Nickname != "" {
fmt.Println("show nickname")
}
Rejecting blank-but-required values after trimming
Sometimes a string is not technically empty, but only contains spaces:
if strings.TrimSpace(input) == "" {
fmt.Println("input is blank")
}
This is important in forms and APIs, where " " should often count as missing.
Real Codebase Usage
In real Go codebases, developers usually use direct string comparison for simple empty checks:
if cfg.Host == "" {
return errors.New("host is required")
}
Common patterns
Guard clauses
func sendEmail(to string) error {
if to == "" {
return errors.New("recipient is required")
}
// continue processing
return nil
}
This keeps invalid input checks near the top of the function.
Early returns
func displayName(name string) string {
if name == "" {
return "Anonymous"
}
return name
}
Validation logic
{
strings.TrimSpace(username) == {
errors.New()
}
}
Common Mistakes
1. Checking for empty when you really mean blank
This only detects a truly empty string:
if input == "" {
fmt.Println("empty")
}
But this string is not empty:
input := " "
If spaces should count as empty, use:
if strings.TrimSpace(input) == "" {
fmt.Println("blank")
}
2. Using len when direct comparison is clearer
This works:
if len(name) > 0 {
fmt.Println("has value")
}
But for a simple empty check, many Go developers find this clearer:
if name != "" {
fmt.Println("has value")
}
3. Forgetting that strings are never nil
A plain Go string cannot be nil.
Comparisons
| Approach | Example | Good for | Notes |
|---|---|---|---|
| Direct comparison | myString != "" | Checking empty/non-empty strings | Most idiomatic for simple emptiness checks |
| Length check | len(myString) > 0 | When size matters or you already use length | Also correct, but less direct for emptiness |
| Trim then compare | strings.TrimSpace(myString) != "" | Ignoring whitespace-only input | Useful for forms and user input |
myString != "" vs len(myString) > 0
| Question | Better choice |
|---|
Cheat Sheet
// empty string check
if s == "" {
// empty
}
// non-empty string check
if s != "" {
// not empty
}
// also valid
if len(s) > 0 {
// not empty
}
// blank after trimming spaces
if strings.TrimSpace(s) == "" {
// empty or whitespace-only
}
Rules
- Idiomatic empty check:
s == ""ors != "" len(s)is valid but usually used when length matters- A Go
stringcannot benil - The zero value of a string is
"" len(s)returns bytes, not necessarily visible characters
Quick choices
- Simple emptiness →
s == "" - Simple non-emptiness →
s != ""
FAQ
Is myString != "" the idiomatic way in Go?
Yes. For a simple empty or non-empty check, direct comparison with "" is usually the clearest and most idiomatic choice.
Is len(myString) > 0 wrong in Go?
No. It is completely valid. It is just a little less direct when your only goal is to test for emptiness.
Which is faster: myString != "" or len(myString) > 0?
For normal code, the performance difference is not important. Choose the version that communicates your intent most clearly.
Can a string be nil in Go?
No. A plain string cannot be nil. Its zero value is the empty string, "".
How do I check for a string that contains only spaces?
Use strings.TrimSpace:
if strings.TrimSpace(s) == "" {
// blank input
}
Should I always use len for strings in Go?
No. Use len when you care about string length. Use direct comparison when you care about emptiness.
Mini Project
Description
Build a small Go program that validates user profile input before saving it. This demonstrates the difference between checking for an empty string and checking for a blank string that contains only whitespace.
Goal
Create a validator that rejects missing or whitespace-only values for required fields.
Requirements
- Create a function that validates a username and email.
- Reject values that are empty strings.
- Reject values that contain only whitespace.
- Print a success message when both values are valid.
Keep learning
Related questions
Check if a Value Exists in a Slice in Go
Learn how to check whether a value exists in a slice in Go, and why Go has no Python-style `in` operator for arrays or slices.
Concatenating Slices in Go with append
Learn how to concatenate two slices in Go using append and the ... operator, with examples, pitfalls, and practical usage.
Convert String to Integer in Go: Idiomatic Parsing with strconv.Atoi
Learn the idiomatic way to convert a string to an int in Go using strconv.Atoi, with examples, errors, and common mistakes.