How to check if a string is empty in Golang

Overview

In this shot, we will learn to check if a string is empty or not.

In Golang, we can do this by:

  • Comparing it with an empty string.
  • Evaluating the length of the string; if it’s zero, then the string is empty, and vice versa.

Example 1

The code below shows how to check if a string is empty by comparing it with an empty string:

package main
import (
"fmt"
)
func main() {
// initialize an empty and a non-empty string
str1 := ""
str2 := "edpresso"
if str1 == "" {
// will be printed on the console, since str1 is empty
fmt.Println("String 1 is empty")
}
if str2 == "" {
// will be skipped, since str2 is not empty
fmt.Println("String 2 is empty")
}
}

Example 2

The code below shows how to check if a string is empty by evaluating the length of the string:

package main
import (
"fmt"
)
func main() {
// initialize an empty and a non-empty string
str1 := ""
str2 := "edpresso"
if len(str1) == 0 {
// will be printed on the console, since str1 is empty
fmt.Println("String 1 is empty")
}
if len(str2) == 0 {
// will be skipped, since str2 is not empty
fmt.Println("String 2 is empty")
}
}

Note: If a string contains only white spaces, we can use the TrimSpace() method to remove them before checking if it’s empty or not.

Free Resources