You can check if a string is whitespace in Golang by using the unicode.IsSpace() function. The unicode.IsSpace() function checks if a given Unicode code point is a whitespace character.
Example 1
package main
import (
"fmt"
"unicode"
)
func main() {
str := " " // a string containing only whitespace
// loop through each character in the string
for _, c := range str {
// check if the character is a whitespace character
if !unicode.IsSpace(c) {
fmt.Println("String is not whitespace")
return
}
}
fmt.Println("String is whitespace")
}
Output
String is whitespace
In this code example, the unicode.IsSpace() function checks if each character in the string is a whitespace character. Since we provided a string with only whitespace runes, it returns the “String is whitespace” output.
The program will output “String is whitespace” if the string contains only whitespace characters. Otherwise, it will output “String is not whitespace”.
Example 2
Let’s pass the non-whitespace string and see what the output is.
package main
import (
"fmt"
"unicode"
)
func main() {
str := "KRU" // a string containing non-whitespace runes
// loop through each character in the string
for _, c := range str {
// check if the character is a whitespace rune
if !unicode.IsSpace(c) {
fmt.Println("String is not whitespace")
return
}
}
fmt.Println("String is whitespace")
}
Output
String is not whitespace
Conclusion
There is a big difference between a string containing a whitespace character and a string being a whitespace character. In this article, we checked if a string is a whitespace character.
Use the unicode.IsSpace() function to check if a string is a whitespace in Golang.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.