What is the best way to test for an empty string in Go?

前端 未结 10 665
终归单人心
终归单人心 2021-01-29 20:26

Which method is best (more idomatic) for testing non-empty strings (in Go)?

if len(mystring) > 0 { }

Or:

if mystring != \"\"         


        
10条回答
  •  再見小時候
    2021-01-29 20:44

    This would be more performant than trimming the whole string, since you only need to check for at least a single non-space character existing

    // Strempty checks whether string contains only whitespace or not
    func Strempty(s string) bool {
        if len(s) == 0 {
            return true
        }
    
        r := []rune(s)
        l := len(r)
    
        for l > 0 {
            l--
            if !unicode.IsSpace(r[l]) {
                return false
            }
        }
    
        return true
    }
    

提交回复
热议问题