How to Check If a String is Empty in Golang [3 Ways]

An empty string in Go is a string that has zero length and no characters. It can be represented by a pair of double quotes with nothing in between, such as “”.

Here are three ways to check if a string is empty in Go:

  1. Using “comparison == operator”
  2. Comparing “length of the string to 0”
  3. Using “strings.TrimSpace() function”

Method 1: Comparing an input string with an empty string

Diagram of Comparing an input string with an empty string

Let’s compare an input string with an empty string.

package main

import (
  "fmt"
)

func main() {
  stringFirst := ""
  stringSecond := "LastOfUs"

  if stringFirst == "" {
    fmt.Println("String First is empty")
  }

  if stringSecond == "" {
    fmt.Println("String Second is empty")
  }
}

Output

String First is empty

Method 2: Comparing the length of the string to 0

Diagram of Comparing the length of the string to 0

Use the len() function to check if the length of the string is 0, and if it does, the string is empty otherwise, it does not.

package main

import (
  "fmt"
)

func main() {
  stringFirst := ""
  stringSecond := "LastOfUs"

  if len(stringFirst) == 0 {
    fmt.Println("String First is empty")
  }

  if len(stringSecond) == 0 {
    fmt.Println("String Second is empty")
  }
}

Output

String First is empty

Method 3: Using the strings.TrimSpace() function

Diagram of Using the strings.TrimSpace() function

Golang strings.TrimSpace() function removes leading and trailing whitespace characters from a string.

If the strings.TrimSpace(main_string) function returns an empty string, which means that the original string only contained whitespace characters.

package main

import (
  "fmt"
  "strings"
)

func main() {
  stringFirst := " \n\t"
  if strings.TrimSpace(stringFirst) == "" {
    fmt.Println("The string only contains whitespace characters, and it is empty")
  } 
  else {
    fmt.Println("The string contains non-whitespace characters.")
  }
}

Output

The string only contains whitespace characters, and it is empty

Which method should you use and why?

For most scenarios, the comparison == operator is straightforward and idiomatic.

If you are only interested in ensuring the string isn’t a zero-length string, the length comparison is a clear choice.

To ensure that a string isn’t empty and doesn’t just contain whitespace (like spaces, tabs, or newlines), strings.TrimSpace() is the best method. However, always be aware of the performance implications if dealing with large strings.

Related posts

Write Multiline Strings in Go

Check If String Contains Substring in Go

Check If String is Alphanumeric in Go