Take an operation on arrays, squaring the length for example.
It's useful to have a generic type (such as f32
, f64
), but you may also want a generic length, but not a dynamic length.
Here is an example of a squared function that takes 2 arguments.
use std::ops::{Add, AddAssign, Sub, Mul};
const CAN_THIS_BE_GENERIC: usize = 2;
fn squared_length<T>(
a: &[T; CAN_THIS_BE_GENERIC],
b: &[T; CAN_THIS_BE_GENERIC]
) -> T
where T:
Copy +
Add +
AddAssign +
Add<Output=T> +
Sub<Output=T> +
Mul<Output=T>
{
let mut d: T = a[0] - a[0]; // zero :(
for (elem_a, elem_b) in a.iter().zip(b.iter()) {
let elem_dim: T = *elem_a - *elem_b;
d += elem_dim * elem_dim;
}
return d;
}
fn main() {
println!("Length A! {}", squared_length::<f64>(&[0.5, 3.5], &[10.0, 0.0]));
println!("Length B! {}", squared_length::<i32>(&[10, -6], &[4, 8]));
println!("Length C! {}", squared_length::<f32>(&[-3.0, 0.0], &[9.0, 0.0]));
}
Currently the vector length is set at 2.
Is it possible to define generic functions where the size is not dynamic, but generic, the same way types can be generic?