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 whitespace in Golang.

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.