Error: non-scalar cast: f64 as f32


#1

I don’t understand what this error means:
error: non-scalar cast: f64 as f32
in this code:

pub trait NumCast: Copy {
    fn cast<T>(n: T) -> Self;
}

impl NumCast for f32 {
    fn cast<f64>(n: f64) -> Self {
        n as f32
    }
}

fn main() {
    println!("{:?}", f32::cast(3.445_f64));
}

https://play.rust-lang.org/?gist=3fa99ee4e50a3f5dc3a94194b5ff754e&version=nightly&backtrace=0


#2

You are declaring a type variable named f64 here.

fn cast<f64>(n: f64) -> Self {
    n as f32
}

// is equivalent to

fn cast<T>(n: T) -> Self {
    n as f32
}

Generic trait methods can’t be "specialize"d, since that will break contract of your trait declaration (types implementing NumCast have fn cast<T> for any T).

Make T a type parameter of trait so that f32 can implement NumCast<f64> which has a method fn cast(f64) -> f32.

pub trait NumCast<T>: Copy {
    fn cast(n: T) -> Self;
}

impl NumCast<f64> for f32 {
    fn cast(n: f64) -> Self {
        n as f32
    }
}