为什么在golang中,strings.Split返回的空数组长度为1?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年3月8日 19:32:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/35866221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定