Skip to content

Use math/rand/v2 in place of math/rand #5335

@mauri870

Description

@mauri870

Describe the enhancement:

In Go 1.22 we got a new package math/rand/v2 that replaces the aging math/rand.

Some improvements include better performance and scalability as well as safer algorithms. See Evolving the Go Standard Library with math/rand/v2.

Since our go.mod file requires go1.22.4 minimum we can safely depend on this new package.

What is the definition of done?

All occurrences of math/rand are replaced with math/rand/v2.

Grepping for math/rand usage I got:

$ rg -l '"math/rand"' | xargs rg 'rand\.'
main.go
39:     rand.Seed(time.Now().UnixNano())

internal/pkg/scheduler/scheduler.go
133:    return time.Duration(rand.Int63n(t))

magefile.go
2109:           bkpName := fmt.Sprintf("./env.sh-%d", rand.Int())

internal/pkg/remote/client.go
267:    rand.Shuffle(len(clients), func(i, j int) {

internal/pkg/core/backoff/equal_jitter.go
33:             nextRand: time.Duration(rand.Int63n(int64(init))), //nolint:gosec
54:     b.nextRand = time.Duration(rand.Int63n(int64(b.duration)))

testing/integration/install_test.go
337:    rand.Seed(time.Now().UnixNano())
342:            runes[i] = letters[rand.Intn(len(letters))]

internal/pkg/agent/cmd/enroll_cmd.go
707:    t := time.NewTimer(time.Duration(rand.Int63n(int64(d))))

internal/pkg/agent/application/upgrade/marker_access_test.go
162:            rune := chars[rand.Intn(len(chars))]

internal/pkg/agent/application/upgrade/artifact/download/http/verifier_test.go
114:    first := rand.Intn(len(tt))
115:    second := rand.Intn(len(tt))
  • rand.Seed(time.Now().UnixNano()) rand.Seed is deprecated since 1.20 and removed in v2, see refactor: remove calls to deprecated rand.Seed function #5334
  • rand.Int stays in v2, no changes needed.
  • rand.Intn stays in v2 as rand.IntN
  • rand.Int63n(x) can now be written as rand.N(x) as stated in the blog post.
  • rand.Shuffle stays the same and gains some perf improvements as stated in the blog post.

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions