| 1 |
Test of fixing redundant calls to maps.Keys and maps.Values |
| 2 |
(both stdlib "maps" and "golang.org/x/exp/maps") for Go 1.21, |
| 3 |
before range over int made suggesting a fix for a rare case easier. |
| 4 |
|
| 5 |
-- go.mod -- |
| 6 |
module maprange |
| 7 |
|
| 8 |
require golang.org/x/exp v0.0.0 |
| 9 |
|
| 10 |
replace golang.org/x/exp => ./exp |
| 11 |
|
| 12 |
go 1.21 |
| 13 |
|
| 14 |
-- old.go -- |
| 15 |
package old |
| 16 |
|
| 17 |
import "golang.org/x/exp/maps" |
| 18 |
|
| 19 |
func _() { |
| 20 |
m := make(map[int]int) |
| 21 |
|
| 22 |
for i := range maps.Keys(m) { // want `likely incorrect use of golang.org/x/exp/maps.Keys \(returns a slice\)` |
| 23 |
_ = i |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
-- old.go.golden -- |
| 28 |
package old |
| 29 |
|
| 30 |
import "golang.org/x/exp/maps" |
| 31 |
|
| 32 |
func _() { |
| 33 |
m := make(map[int]int) |
| 34 |
|
| 35 |
for i := range maps.Keys(m) { // want `likely incorrect use of golang.org/x/exp/maps.Keys \(returns a slice\)` |
| 36 |
_ = i |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
-- exp/go.mod -- |
| 41 |
module golang.org/x/exp |
| 42 |
|
| 43 |
go 1.21 |
| 44 |
|
| 45 |
-- exp/maps/maps.go -- |
| 46 |
package maps |
| 47 |
|
| 48 |
func Keys[M ~map[K]V, K comparable, V any](m M) []K { |
| 49 |
r := make([]K, 0, len(m)) |
| 50 |
for k := range m { |
| 51 |
r = append(r, k) |
| 52 |
} |
| 53 |
return r |
| 54 |
} |
| 55 |
|
| 56 |
func Values[M ~map[K]V, K comparable, V any](m M) []V { |
| 57 |
r := make([]V, 0, len(m)) |
| 58 |
for _, v := range m { |
| 59 |
r = append(r, v) |
| 60 |
} |
| 61 |
return r |
| 62 |
} |