// PermittedValue uses a generic value
func PermittedValue[T comparable](value T, permittedValues ...T) bool {
for i := range permittedValues {
if value == permittedValues[i] {
return true
}
}
code
return false
}
Am getting the lint error "Loop can be simplified using slices.Contains
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The lint error "Loop can be simplified using slices.Contains" is telling you that the pattern you're using (looping through a slice to check for an element's existence) is so common that Go 1.21 introduced a dedicated function for it in the slices package.
Here's how you can simplify your function:
go
package main // or your package name
import "slices" // Import the new slices package
// PermittedValue uses a generic value
func PermittedValue[T comparable](value T, permittedValues ...T) bool {
// slices.Contains efficiently checks if 'value' exists within the 'permittedValues' slice.
return slices.Contains(permittedValues, value)
}
func main() {
// Example usage:
println(PermittedValue("apple", "apple", "banana", "orange")) // true
println(PermittedValue(10, 1, 5, 10, 20)) // true
println(PermittedValue(false, true, false)) // true
println(PermittedValue("grape", "apple", "banana")) // false
println(PermittedValue(99, 1, 2, 3)) // false
}
Explanation:
import "slices": You need to import the slices package, which was introduced in Go 1.21. If you're on an older Go version, you won't have this package.
slices.Contains(permittedValues, value): This function directly does what your loop was doing. It takes a slice (permittedValues in your case, which is a []T when used as ...T) and an element (value) and returns true if the element is found in the slice, false otherwise.
This change makes your code more concise, readable, and uses the idiomatic Go way of performing this common operation.