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
The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.
Using split()When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.
To declare the type for a variable that holds a slice, use an empty pair of square brackets, followed by the type of elements the slice will hold.
As said in the comments by @u_mulder, the array isn't empty as it contains an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With