Question

How to Check for an Empty String in Go

gostringis-empty

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 string
  • len(myString) > 0 says 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) > 0 asks: 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(...).

Take Quiz

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

  • == "" and != "" clearly communicate what you mean
  • no extra function call is needed in your thinking
  • it matches common Go style for simple emptiness checks

When len is useful

Use len(myString) when you actually care about the size:

if len(password) < 8 {
    fmt.Println("password is too short")
}

Here, length is the real concern, so len is the right tool.

Step by Step Execution

Consider this example:

package main

import "fmt"

func main() {
    s := "hello"

    if s != "" {
        fmt.Println("non-empty")
    }
}

Step by step:

  1. s := "hello"

    • A string variable named s is created.
    • Its value is "hello".
  2. if s != ""

    • Go compares s with the empty string.
    • "hello" != "" is true.
  3. fmt.Println("non-empty")

    • Because the condition is true, this line runs.
    • Output:
non-empty

Now compare with an empty string:

package main

import "fmt"

func main() {
    s := ""

    if s == "" {
        fmt.Println("empty")
    }
}

Step by step:

  1. s := ""

    • s is assigned the empty string.
  2. if s == ""

    • Go compares s to the empty string.
    • "" == "" is true.
  3. fmt.Println("empty")

    • The message is printed.

Using len works similarly:

s := "hello"
if len(s) > 0 {
    fmt.Println("non-empty")
}
  • len(s) becomes 5
  • 5 > 0 is true
  • the line executes

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.

Take Quiz

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

func validateUser(username string) error {
    if strings.TrimSpace(username) == "" {
        return errors.New("username cannot be blank")
    }
    return nil
}

Filtering values

names := []string{"Go", "", "Rust", ""}
var filtered []string

for _, name := range names {
    if name != "" {
        filtered = append(filtered, name)
    }
}

Configuration defaults

if port == "" {
    port = "8080"
}

These patterns appear often in CLI tools, APIs, services, and data processing programs.

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.

Broken idea:

// invalid concept for a plain string
// if s == nil { ... }

A string's zero value is "", not nil.

4. Confusing byte length with character count

len(s) returns the number of bytes, not necessarily the number of human-readable characters.

s := "é"
fmt.Println(len(s)) // may print 2 in UTF-8

This does not affect an empty check, but it matters if you use len for validation.

5. Overcomplicating a simple condition

Avoid unnecessary helpers for simple checks unless your project already uses them consistently.

Too much for basic emptiness:

func hasText(s string) bool {
    return s != ""
}

Usually, inline comparison is simpler.

Comparisons

ApproachExampleGood forNotes
Direct comparisonmyString != ""Checking empty/non-empty stringsMost idiomatic for simple emptiness checks
Length checklen(myString) > 0When size matters or you already use lengthAlso correct, but less direct for emptiness
Trim then comparestrings.TrimSpace(myString) != ""Ignoring whitespace-only inputUseful for forms and user input

myString != "" vs len(myString) > 0

QuestionBetter choice
Is the string empty?myString == "" or myString != ""
Does the string meet a minimum length?len(myString)
Should spaces count as empty?strings.TrimSpace(myString) == ""

Key takeaway

  • Use direct comparison for empty-string checks.
  • Use len when length is the real concern.
  • Use strings.TrimSpace when user input may contain only whitespace.
Take Quiz

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 == "" or s != ""
  • len(s) is valid but usually used when length matters
  • A Go string cannot be nil
  • The zero value of a string is ""
  • len(s) returns bytes, not necessarily visible characters

Quick choices

  • Simple emptiness → s == ""
  • Simple non-emptiness → s != ""
  • Minimum length → len(s) >= n
  • Ignore spaces → strings.TrimSpace(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.

Does len(s) count characters in Go?

Not always. It counts bytes in the string's UTF-8 representation. That is fine for empty checks, but important for character-count logic.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more