0
0
GoHow-ToBeginner · 3 min read

How to Check if String is Empty in Go: Simple Guide

In Go, you check if a string is empty by comparing it to an empty string literal using == "". For example, if myString == "" {} checks if myString has no characters.
📐

Syntax

To check if a string is empty in Go, use the equality operator == to compare the string variable with an empty string literal "".

  • myString: your string variable
  • ==: checks if two values are equal
  • "": empty string literal (no characters)
go
if myString == "" {
    // string is empty
}
💻

Example

This example shows how to check if a string is empty and print a message accordingly.

go
package main

import "fmt"

func main() {
    var s string

    if s == "" {
        fmt.Println("The string is empty.")
    } else {
        fmt.Println("The string is not empty.")
    }

    s = "hello"

    if s == "" {
        fmt.Println("The string is empty.")
    } else {
        fmt.Println("The string is not empty.")
    }
}
Output
The string is empty. The string is not empty.
⚠️

Common Pitfalls

Some common mistakes when checking if a string is empty in Go include:

  • Using len(myString) == 0 is correct but less direct than myString == "".
  • Comparing to nil does not work because strings are not pointers.
  • Using functions like strings.TrimSpace without understanding it removes spaces but does not check emptiness directly.
go
package main

import "fmt"

func main() {
    var s string

    // Wrong: comparing string to nil (won't compile)
    // if s == nil {
    //     fmt.Println("Empty string")
    // }

    // Correct: compare to empty string
    if s == "" {
        fmt.Println("String is empty")
    }
}
Output
String is empty
📊

Quick Reference

Here is a quick summary of ways to check if a string is empty in Go:

MethodDescriptionExample
Equality checkCompare string to empty string literalif s == "" {}
Length checkCheck if string length is zeroif len(s) == 0 {}

Key Takeaways

Use myString == "" to check if a string is empty in Go.
Avoid comparing strings to nil because strings are not pointers.
You can also use len(myString) == 0 but == "" is clearer.
Remember that empty string means zero characters, not spaces or other whitespace.
Always test your string checks with both empty and non-empty values.