How to check if a string is blank (empty, nil, or contains only whitespace) in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "unicode"
)

func isBlankOrEmpty(str *string) bool {
    // Check for nil or empty string
    if str == nil || *str == "" {
        return true
    }

    // Check if the string contains only whitespace
    for _, ch := range *str {
        if !unicode.IsSpace(ch) {
            return false // Found a non-whitespace character
        }
    }

    return true
}

func main() {
    testCases := []*string{
        nil,
        new(string),
        func() *string { s := "   "; return &s }(),
        func() *string { s := "abc"; return &s }(),
    }

    for i, test := range testCases {
        fmt.Printf("Test%d: %t\n", i+1, isBlankOrEmpty(test))
    }
}


/*
run:

Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 8, 2025 by avibootz
...