MCPcopy Index your code
hub / github.com/coder/coder / Element

Function Element

cryptorand/slices.go:9–20  ·  view source on GitHub ↗

Element returns a random element of the slice. An error will be returned if the slice has no elements in it.

(s []T)

Source from the content-addressed store, hash-verified

7// Element returns a random element of the slice. An error will be returned if
8// the slice has no elements in it.
9func Element[T any](s []T) (out T, err error) {
10 if len(s) == 0 {
11 return out, xerrors.New("slice must have at least one element")
12 }
13
14 i, err := Intn(len(s))
15 if err != nil {
16 return out, xerrors.Errorf("generate random integer from 0-%v: %w", len(s), err)
17 }
18
19 return s[i], nil
20}

Callers 1

TestRandomElementFunction · 0.92

Calls 3

IntnFunction · 0.85
NewMethod · 0.65
ErrorfMethod · 0.45

Tested by 1

TestRandomElementFunction · 0.74