【发布时间】:2020-04-25 21:03:09
【问题描述】:
分割字符串时,使用strings.Split,如果输入字符串为空,则生成的空切片长度为1。
package main
import (
"strings"
"fmt"
)
func main() {
emptySlice1 := []string{}
debugSlice( emptySlice1 ) // prints "[], []string, len 0"
someStringToSplit := ""
emptySlice2 := strings.Split(someStringToSplit , " ")
debugSlice( emptySlice2 ) // prints "[], []string, len 1"
}
func debugSlice( s []string ){
fmt.Printf("%v, %T, len %v\n", s, s, len(s))
}
游乐场可以在这里找到:https://play.golang.org/p/kBYR048UtP_0
这是为什么呢?
如何检查切片中的实际项目数(如果不是 len 函数)?
【问题讨论】: