Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace sort usage with slices equivalents #63

Open
dnwe opened this issue Aug 30, 2023 · 0 comments
Open

Replace sort usage with slices equivalents #63

dnwe opened this issue Aug 30, 2023 · 0 comments

Comments

@dnwe
Copy link
Contributor

dnwe commented Aug 30, 2023

As per https://go.dev/blog/go1.21 :

the new slices package (neé golang.org/x/slices) includes sorting functions that are generally faster and more ergonomic than the sort package

Doing this in ruleguard for sort.Strings is quite trivial:

// sort.Strings => slices.Sort
func sortStrings(m dsl.Matcher) {
	m.Match(
		`sort.Strings($s)`,
	).Where(m["s"].Type.Is("[]string")).
		Report(`As of Go 1.21, slices.Sort is a faster and more ergonomic choice.`).
		Suggest(`slices.Sort($s)`)
}

But sort.Func --> slices.SortFunc is a little trickier as you need the type of the slice to use as the param type in the cmp func
e.g.,

-	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
+	slices.SortFunc(keys, func(a, b int32) int { return int(a - b) })

and I don't think it's possible for ruleguard to infer this?

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

No branches or pull requests

1 participant