对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
当前回答
使用下面这样的函数会更简洁,更不容易出错:
func empty(s string) bool {
return len(strings.TrimSpace(s)) == 0
}
其他回答
这似乎是不成熟的微优化。编译器可以为这两种情况或至少为这两种情况生成相同的代码
if len(s) != 0 { ... }
and
if s != "" { ... }
因为语义显然是相等的。
这两种样式都在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的帖子中写道:
使代码清晰的那个。 如果我要查看元素x,我通常会写 len(s) >x,即使x == 0,但如果我关心 "是这个特定的字符串"我倾向于写s == "" 假设一个成熟的编译器会编译是合理的 Len (s) == 0和s == ""变成了同样高效的代码。 ... 使代码清晰。
正如Timmmm的回答所指出的,在这两种情况下,Go编译器确实生成了相同的代码。
检查长度是一个很好的答案,但您也可以解释一个“空”字符串,它也只是空白。严格来说不是空的,但如果你愿意检查:
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!")
}
}
假设空格和所有前导和后面的空格都应该被删除:
import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }
因为: Len("") //为0 Len(" ") //一个空格为1 Len(" ") //两个空格为2
使用下面这样的函数会更简洁,更不容易出错:
func empty(s string) bool {
return len(strings.TrimSpace(s)) == 0
}