| // Generic Programming: Static Polymorphism |
| |
| #![allow(dead_code)] |
| #![allow(unused_imports)] |
| |
| use rust_tutorial::*; |
| |
| /// Run this to see the disassembly of `compute_sum_of_squares_{1,2}`: |
| /// |
| /// ```bash |
| /// cargo objdump --bin tut3 --release -- -d | awk -v RS= '/^([[:xdigit:]]+ )?tut3::compute_sum_of_squares/' |
| /// ``` |
| |
| #[inline(never)] |
| fn compute_sum_of_squares_i32(zero: i32, xs: &Vec<i32>) -> i32 { |
| xs[1..].iter() |
| .map(|x| x * x) |
| .fold(zero, |acc, x| acc + x) |
| } |
| |
| #[inline(never)] |
| fn compute_sum_of_squares<T>(zero: T, xs: &Vec<T>) -> T |
| where |
| T: std::ops::Mul<Output=T> + std::ops::Add<Output=T> + Copy |
| { |
| xs[1..].iter() |
| .map(|x| *x * *x) |
| .fold(zero, |acc, x| acc + x) |
| } |
| |
| fn main() { |
| let numbers = vec![1, 2, 3, 4, 5]; |
| |
| let sum_of_squares_i32 = compute_sum_of_squares_i32(0, &numbers); |
| let sum_of_squares_t = compute_sum_of_squares(0, &numbers); |
| |
| println!("sum i32 = {}", sum_of_squares_i32); |
| println!("sum T = {}", sum_of_squares_t); |
| } |