首页 文章

在Go中测试空字符串的最佳方法是什么?

提问于
浏览
178

对于测试非空字符串(在Go中)哪种方法最好(更像是idomatic)?

if len(mystring) > 0 { }

要么:

if mystring != "" { }

或者是其他东西?

7 回答

  • 25

    两种样式都在Go的标准库中使用 .

    if len(s) > 0 { ... }
    

    可以在 strconv 包中找到:http://golang.org/src/pkg/strconv/atoi.go

    if s != "" { ... }
    

    可以在 encoding/json 包中找到:http://golang.org/src/pkg/encoding/json/encode.go

    两者都是惯用的,并且足够清晰 . 这更多的是个人品味和清晰度 .

    Russ Cox写道golang-nuts thread

    使代码清晰的那个 . 如果我要查看元素x,我通常写len(s)> x,即使对于x == 0,但是如果我关心“是这个特定字符串”我倾向于写s ==“” . 假设成熟的编译器将len(s)== 0和s ==“”编译成相同的高效代码是合理的 . 现在6g等编译s ==“”进入函数调用,而len(s)== 0不是,但这已经在我的待办事项列表中修复 . 使代码清晰 .

  • 1

    这似乎是过早的微观优化 . 编译器可以自由地为两种情况生成相同的代码,或至少为这两种情况生成相同的代码

    if len(s) != 0 { ... }
    

    if s != "" { ... }
    

    因为语义明显相等 .

  • 5

    检查长度是一个很好的答案,但您也可以考虑一个“空”字符串,它也只是空格 . 不是“技术上”空的,但如果你想检查:

    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!")
      }
    }
    
  • 269

    假设应删除空格和所有前导和尾随空格:

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

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

  • 0

    截至目前,Go编译器在两种情况下都生成相同的代码,因此这是一个品味问题 . GCCGo会生成不同的代码,但几乎没有人使用它,所以我不担心 .

    https://godbolt.org/z/fib1x1

  • 15

    使用类似下面的函数会更干净,更不容易出错:

    func empty(s string) bool {
        return len(strings.TrimSpace(s)) == 0
    }
    
  • 0

    这比修剪整个字符串更有效,因为您只需检查至少一个非空格字符

    // 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
    }
    

相关问题