Skip to content

Conversation

@dnwe
Copy link
Contributor

@dnwe dnwe commented Sep 11, 2025

Use strings.Cut instead of strings.SplitN for cleaner string splitting

).
Suggest(`$x, _, _ := strings.Cut($y, $delim)`).
Report(`Use strings.Cut instead of strings.SplitN for cleaner string splitting`)
m.Match(`$x := strings.SplitN($y, $delim, 2)[1]`).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My point was also to add SplitN -1 and Split for [1]

As you can see there are some out there.

Copy link
Contributor Author

@dnwe dnwe Sep 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I wrote this rule to catch "someone wrote valid and reasonable code with a clear intent (split into exactly two values), but it could be done in a cleaner more readable way that achieves the exact same result, here is an autofix to tidy that up for you" approach – a bit like the new gopls modernize package.

For $x := strings.Split($y, $delim)[1] and $x := strings.SplitN($y, $delim, -1)[1] the autofix is only valid if there are exactly two elements because the [1] equivalent in strings.Cut is "after", i.e., all elements after the delimiter, not just the second element alone

So whilst these two lines are equivalent:

port := strings.Split("host:port", ":")[1]
_, port, _ := strings.Cut("host:port", ":")

These two are not

want := strings.Split("a,b,c", ",")[1]
_, got, _ := strings.Cut("a,b,c", ",")
string differs (-got, +want):
  string(
- 	"b,c",
+ 	"b",
  )

(playground link)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right.

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