-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Open
Labels
ToolProposalIssues describing a requested change to a Go tool or command-line program.Issues 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.This label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.Issues related to the Go language server, gopls.help wanted
Milestone
Description
gopls version
N/A
go env
N/AWhat did you do?
N/A
What did you see happen?
N/A
What did you expect to see?
- strings.Cut was added in Go 1.18
- strings.CutPrefix and strings.CutSuffix were added in Go 1.20
But these operators are not commonly used, we can find code that are doing things like that
strings.Split(s, sep)[0]: 140kstrings.Split(s, sep)[1]: 58kstrings.SplitN(s, sep, 2)[0]23kstrings.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
adonovan, alexandear and servusdei2018
Metadata
Metadata
Assignees
Labels
ToolProposalIssues describing a requested change to a Go tool or command-line program.Issues 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.This label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.Issues related to the Go language server, gopls.help wanted