对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
当前回答
到目前为止,Go编译器在这两种情况下生成相同的代码,所以这是一个品味问题。GCCGo确实会生成不同的代码,但几乎没有人使用它,所以我不担心这个问题。
https://godbolt.org/z/fib1x1
其他回答
使用下面这样的函数会更简洁,更不容易出错:
func empty(s string) bool {
return len(strings.TrimSpace(s)) == 0
}
这似乎是不成熟的微优化。编译器可以为这两种情况或至少为这两种情况生成相同的代码
if len(s) != 0 { ... }
and
if s != "" { ... }
因为语义显然是相等的。
到目前为止,Go编译器在这两种情况下生成相同的代码,所以这是一个品味问题。GCCGo确实会生成不同的代码,但几乎没有人使用它,所以我不担心这个问题。
https://godbolt.org/z/fib1x1
这将比修整整个字符串的性能更好,因为您只需要检查至少一个存在的非空格字符
// 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
}
假设空格和所有前导和后面的空格都应该被删除:
import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }
因为: Len("") //为0 Len(" ") //一个空格为1 Len(" ") //两个空格为2