Expand description
Efficiently find items by matching weight. If your data is static, you can build the lookup structure (a complete binary tree) at compile time.
You can use any inferred numeric type for the weights. You can have any range for the lookup, by default 0.0 .. 1.0 for floats, and their respective whole spectrum MIN ..= MAX for integers.
As a small example, let’s make red more than twice as likely as green, and that in turn five times as likely as blue.
let colours = weights! {
0.70 => "red",
0.25 => "green",
0.05 => "blue",
};
// If you have dynamic values, use this macro instead:
let frequent = 0.70;
let most = "red";
let dyn_colours = dyn_weights! {
frequent => most,
0.25 => "green",
0.05 => "blue",
};
// Any random source of the same type and range as your weights will do.
println!("I got {}", colours.get(rand_f32()));
println!("I got {}", dyn_colours.get(rand_f32()));There’s a blog about the design choices behind this.
Macros§
- dyn_
weights - This is the dynamic constructor for
Weights. If you do not need to feed in dynamic values, use its compile time equivalent weights!{}. Also see that for the details, which are otherwise identical. - weights
- This is the compile time constructor for
Weights. If you need to feed in dynamic values, use the run time equivalent dyn_weights!{}.
Structs§
- Weights
- This is the underlying data type, which you construct via weights!{} or dyn_weights!{}.
For returning or defining a
static, you will need to specify this type exactly. In that case you can bind it to a variable, and let rust-analyzer add the type details.