Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty array returned from strings.Split have a length of 1 in golang?

Tags:

go

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

like image 881
wybourn Avatar asked Mar 08 '16 11:03

wybourn


People also ask

Why does split return empty string?

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.

Does split return empty string?

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.

What is meant by empty slice in Golang?

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.


1 Answers

As said in the comments by @u_mulder, the array isn't empty as it contains an empty string.

like image 124
wybourn Avatar answered Oct 21 '22 04:10

wybourn