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

前端 未结 10 895
终归单人心
终归单人心 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:55

    Assuming that empty spaces and all leading and trailing white spaces should be removed:

    import "strings"
    if len(strings.TrimSpace(s)) == 0 { ... }
    

    Because :
    len("") // is 0
    len(" ") // one empty space is 1
    len(" ") // two empty spaces is 2

提交回复
热议问题