generic-cast 0.1.0

Cast generic type-parameters to types
Documentation
  • Coverage
  • 0%
    0 out of 4 items documented0 out of 3 items with examples
  • Size
  • Source code size: 2.84 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.04 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • Homepage
  • keyvank/generic-cast
    5 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • keyvank

generic-cast

Imagine you want to provide an alternative implementation for a specific type-parameter of a generic function:

use generic_cast::{cast_ref, equals};
use std::ops::Add;

fn double<T: 'static + Copy + Add<Output = T>>(a: T) -> T {
    if let Some(a) = cast_ref::<T, u32>(&a) {
        let result = a << 1; // Faster implementation
        *cast_ref::<u32, T>(&result).unwrap()
    } else {
        a.add(a).clone()
    }
}

Or maybe just check if the type-paramter is a specific type:

fn print<T: 'static + std::fmt::Display>(a: T) {
    if generic_cast::equals::<T, f32>() {
        println!("Its a float!");
    }
    println!("{}", a);
}