Weighted Random Choice
Pick items with arbitrary positive weights using one random draw, rejecting bad weights and checking the distribution.
Code
package main
import (
"errors"
"fmt"
"math/rand"
)
type Choice[T any] struct {
Item T
Weight float64
}
func Pick[T any](r *rand.Rand, choices []Choice[T]) (T, error) {
var zero T
if len(choices) == 0 {
return zero, errors.New("no choices")
}
total := 0.0
for _, choice := range choices {
if choice.Weight < 0 {
return zero, fmt.Errorf("negative weight for %v", choice.Item)
}
total += choice.Weight
}
if total <= 0 {
return zero, errors.New("total weight must be positive")
}
target := r.Float64() * total
for _, choice := range choices {
if target < choice.Weight {
return choice.Item, nil
}
target -= choice.Weight
}
return choices[len(choices)-1].Item, nil
}
func main() {
rng := rand.New(rand.NewSource(42))
choices := []Choice[string]{
{Item: "canary", Weight: 1},
{Item: "stable", Weight: 3},
{Item: "legacy", Weight: 6},
}
counts := map[string]int{}
for i := 0; i < 10000; i++ {
item, err := Pick(rng, choices)
if err != nil {
panic(err)
}
counts[item]++
}
for _, choice := range choices {
fmt.Printf("%s weight=%.0f picked=%d (%.1f%%)\n", choice.Item, choice.Weight, counts[choice.Item], float64(counts[choice.Item])/100)
}
_, err := Pick(rng, []Choice[string]{{Item: "bad", Weight: -1}})
fmt.Println("negative weight rejected:", err != nil)
}How the snippet works
Weighted Random Choice is built around the function main.
Iteration happens inside for _, choice := range choices — everything outside it runs once. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Errors are ordinary return values; skipping the
errcheck means using a zero value silently.
Applying it
The demo output is labeled (negative weight rejected:); each label names the call that printed it.
Statements that matter
return zero, fmt.Errorf("negative weight for %v", choice.Item)
return zero, errors.New("total weight must be positive")
return zero, errors.New("no choices")
Interactive Tools for This Topic
Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.
FAQ
- How do errors reach the caller?
- By return value: each fallible call hands back an `error`, checked at 1 place here.
- What does Weighted Random Choice print when run?
- Execute the whole file; each printed line is prefixed with a label like `negative weight rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.