Skip to content

x/tools/gopls: modernize could suggest using strings.Cut* instead of strings.Split* #74494

Open
@ccoVeille

Description

@ccoVeille

gopls version

N/A

go env

N/A

What did you do?

N/A

What did you see happen?

N/A

What did you expect to see?

But these operators are not commonly used, we can find code that are doing things like that

  • strings.Split(s, sep)[0] : 140k
  • strings.Split(s, sep)[1]: 58k
  • strings.SplitN(s, sep, 2)[0] 23k
  • strings.SplitN(s, sep, 2)[1]: 8k

And all variations like, that are not as easy to spot with GitHub search.

	items := strings.Split(s, sep)
	before := items[0]
	items := strings.Split(s, sep)
	before := items[0]
	after := items[1]

I would like code to suggest using strings.Cut, as stated in the documentation of strings.Split

To split around the first instance of a separator, see Cut.

Also, strings.CutPrefix and strings.CutSuffix could be used.

Here are the

a := strings.Split(s, sep)[0]       // want a, _ := strings.CutSuffix(s, sep)
b := strings.Split(s, sep)[1]       // want b, _ := strings.CutPrefix(s, sep)
c := strings.SplitN(s, sep, 2)[0] // want c, _ := strings.CutSuffix(s, sep)
d : strings.SplitN(s, sep, 2)[1]   // want d, _ := strings.CutSuffix(s, sep)

And about this one, that can panic if the separator is not found.

items := strings.Split(s, sep)
before := items[0]
after := items[1]
before, after, _ := strings.Cut(s, sep)

Here I'm assuming items is not reused.

Please note there are code that do things like that

items := strings.Split(s, sep) // or SplitN(s, sep, 2)
if len(items) < 2 { // or len(items) == 1
	return errors.New("whatever")
}
before := items[0]
after := items[1]

or

items := strings.Split(s, sep) // or SplitN(s, sep, 2)
if len(items) == 2 { // or len(items) != 1
	doSomething(items[0], items[1])
}

They can be easily found among these results

Editor and settings

No response

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    ToolProposalIssues describing a requested change to a Go tool or command-line program.ToolsThis label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.help wanted

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions