Skip to content

fix(go): split(none, n) maxsplit handling like Rust - #1003

Merged
mitsuhiko merged 2 commits into
mitsuhiko:mainfrom
ChandraChaan:fix/go-split-maxsplit
Nov 5, 2026
Merged

mitsuhiko merged 2 commits into
mitsuhiko:mainfrom
ChandraChaan:fix/go-split-maxsplit

Conversation

@ChandraChaan

Copy link
Copy Markdown
Contributor

Follow-up to #1001 for the Go port. splitWhitespaceN (called with n = maxsplit + 1) only checked the split limit after appending a word, so split(none, 0) still split once. When looking for the start of the rest it also indexed bytes and converted them to runes, so multi-byte whitespace such as a non-breaking space was kept at the start of the rest:

Template Go before Rust / Python
{{ "a b c"|split(none, 0) }} ['a', 'b c'] ['a b c']
{{ " a b c "|split(none, 0) }} ['a', 'b c '] ['a b c ']
{{ "a b"|split(none, 1) }} ['a', ' b'] ['a', 'b']

(The "before" values are what the new test rows report on current main; see the CI link below.)

It now follows Python's str.split(None, maxsplit): skip leading whitespace, take at most maxsplit words, and return the rest with its trailing whitespace. The existing split-n-ws cases (e.g. " foo bar baz "|split(none, 1) → ['foo', 'bar baz ']) and the strings.Fields path for no or negative maxsplit are unchanged. Added the three rows above to TestFiltersRejectUnsupportedValuesLikeRust and a changelog entry.

I ran CI on my fork:

splitWhitespaceN only checked the split limit after appending a word, so
split(none, 0) still split once: "a b c"|split(none, 0) gave
['a', 'b c'] instead of ['a b c']. When looking for the start of the
rest it also read single bytes as runes, so multi-byte whitespace such
as a non-breaking space stayed at the start of the rest.

It now follows Python's str.split(None, maxsplit): skip leading
whitespace, take at most maxsplit words, and return the rest with its
trailing whitespace.
@mitsuhiko
mitsuhiko force-pushed the fix/go-split-maxsplit branch from 0f4bf7e to 97710f8 Compare November 5, 2026 21:28
@mitsuhiko
mitsuhiko merged commit 702eacc into mitsuhiko:main Nov 5, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants