英文:
Why does an empty array returned from strings.Split have a length of 1 in golang?
问题
我刚开始学习golang,遇到了一个非常奇怪的问题。当你从strings.Split函数返回一个空数组时,它的长度为1。
示例:
package main
import (
"fmt"
"strings"
)
func main() {
test := strings.Split("", ",")
fmt.Println(test)
fmt.Println(len(test))
}
这将输出:
[]
1
为什么会这样呢?如果这是预期的行为,那么如何正确地检查一个数组是否为空呢?
谢谢。
英文:
I'm just starting out learning golang, and I've encountered something quite strange. When you get an empty array back from a call to strings.Split, it has a length of one.
Example
package main
import (
"fmt"
"strings"
)
func main() {
test := strings.Split("", ",")
fmt.Println(test)
fmt.Println(len(test))
}
This outputs:
[]
1
Why is this? If this is expected behavior, what is the correct way to check if an array is empty?
Thanks
答案1
得分: 8
根据@u_mulder的评论所说,该数组并不为空,因为它包含一个空字符串。
英文:
As said in the comments by @u_mulder, the array isn't empty as it contains an empty string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论