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

前端 未结 10 666
终归单人心
终归单人心 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条回答
  •  -上瘾入骨i
    2021-01-29 20:48

    Checking for length is a good answer, but you could also account for an "empty" string that is also only whitespace. Not "technically" empty, but if you care to check:

    package main
    
    import (
      "fmt"
      "strings"
    )
    
    func main() {
      stringOne := "merpflakes"
      stringTwo := "   "
      stringThree := ""
    
      if len(strings.TrimSpace(stringOne)) == 0 {
        fmt.Println("String is empty!")
      }
    
      if len(strings.TrimSpace(stringTwo)) == 0 {
        fmt.Println("String two is empty!")
      }
    
      if len(stringTwo) == 0 {
        fmt.Println("String two is still empty!")
      }
    
      if len(strings.TrimSpace(stringThree)) == 0 {
        fmt.Println("String three is empty!")
      }
    }
    

提交回复
热议问题