Using the rand crate, I want to implement the following:
/// Univariate standard normal distribtion with pairwise output
#[derive(Clone, Copy, Default, Debug)]
pub struct StdNormDistPair;
impl<T: Num> Distribution<(T, T)> for StdNormDistPair {
/* … */
}
I wondered if it is semantically correct to use the type (T, T) to describe a pair or whether it would be better to make it [T; 2]. I would like to know what's the idiomatic way to describe a "pair of two equally-typed values".
Interestingly, std uses a tuple rather than an array in its sin_cos method. This would be an argument in favor of using tuples.
However, arrays would allow me to iterate, for example.
Following the precedent of multi-dimentional distributions in rand_distr - Rust, such as this one it looks like [F; 2] is the way to go, at least in case consistency with that library is a goal ^^
Compiling playground v0.0.1 (/playground)
error[E0282]: type annotations needed
--> src/main.rs:20:9
|
20 | let [x, y] = Foo.get_pair(); // this fails
| ^^^^^^
|
help: consider giving this pattern a type
|
20 | let [x, y]: /* Type */ = Foo.get_pair(); // this fails
| ++++++++++++
For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (bin "playground") due to previous error
Interestingly, the following simpler example works fine:
fn bar<T: Default>() -> [T; 2] {
Default::default()
}
fn main() {
let mut vec = Vec::<f64>::new();
let [x, y] = bar(); // this works
vec.push(x);
vec.push(y);
}
Removing the tuple impl works because when there's only one implementation, that implementation will be used to guide inference. You can replace the tuple impl with one for f64 or String for that matter and the error will come back.