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:
- Using “comparison == operator”
- Comparing “length of the string to 0”
- Using “strings.TrimSpace() function”
Method 1: 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
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
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
Check If String Contains Substring in Go
Check If String is Alphanumeric in Go

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.