You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It's working correctly. Consider splitting space-delimited text using Split("word", "
"): The result should be {"word"}. Split("w", " ") gives {"w"} and Split("", " ") gives
{""}. It's all consistent: if the separator doesn't appear in th e text, you get the
input back.
It's consistent indeed; it caused me some troubles streamlining a function:
// getFooNames creates a slice of non-empty names from a colon-separated string.
func getFooNames(s string, emptyOK bool) []string {
if len(s) == 0 {
if !emptyOK {
panic("empty string")
}
return string{}
}
names := string.Split(s, ":", -1)
for n := range names {
if len(n) == 0 {
panic("empty name in a list")
}
// ... more validation ...
}
return names
}
into a form without the special-case return at the top:
func getFooNames(s string, emptyOK bool) []string {
names := string.Split(s, ":", -1)
for n := range names {
if len(n) == 0 {
panic("empty name in a list")
}
// ... more validation ...
}
if len(names) == 0 && !emptyOK {
panic("empty list")
}
return names
}
I had assumed the loop would not run for empty s, but it did, and panicked.
The assumption is due to me having worked with Perl, where split("") acts differently.
I've checked out Python's split; it has multiple modes, one of which acts more like
Go's. Python documentation states:
Splitting an empty string with a specified separator returns [''].
It might benefit Perl programmers to mention it as well, e.g.:
Splitting an empty string returns a slice containing empty string as its element.
The text was updated successfully, but these errors were encountered: