0

I'm creating cargo that (among other things) will implement idiomatic angle measurment. When creating methods to convert between angle units I've found problem:

impl<T> Angle<T>
where T: Float {
    pub fn to_deg(self) -> Self {
        Deg(match self {
            Rad(v) =>  v * cast(180.0 / f64::consts::PI).unwrap(),
            Deg(v) =>  v,
            Grad(v) => v * cast(180.0 / 200.0).unwrap() // how to get rid of this cast?
        })
    }
}

Runnable

The cast of 180.0 / 200.0 seem really unneded for me? Is there any way to get rid of this?

When I delete cast then I get:

src/angles.rs:42:28: 42:33 error: mismatched types:
 expected `T`,
    found `_`
(expected type parameter,
    found floating-point variable) [E0308]
src/angles.rs:42             Grad(v) => v * 180.0 / 200.0
                                            ^~~~~
Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • 1
    Please create an [MCVE](http://stackoverflow.com/help/mcve), ideally one that runs on the [Playpen](https://play.rust-lang.org/). This lets us help you with very little friction, making it more likely that you will get a timely and good response. – Shepmaster Feb 03 '15 at 18:08
  • 1
    possible duplicate of [Dividing a const by a generic in Rust](http://stackoverflow.com/questions/27441224/dividing-a-const-by-a-generic-in-rust) – Shepmaster Feb 03 '15 at 18:13
  • 1
    Here's [an example of a **M**CVE](http://is.gd/g4ZXKh) – Shepmaster Feb 03 '15 at 18:18

1 Answers1

0

When you have a generic function with a type parameter, such as T, you don't get to choose the type. The type is forced on you by the caller of the function.

The error here is that you're trying to assign a specific f32/f64 type to a type T, which could be anything that implements Float.

You know in practice it's going to be either one of the floating-point types, but theoretically the type system won't stop someone from implementing Float on a string or an array, or a tuple of two function pointers, or any other bizarre thing that can't be assigned a float. When the compiler can't guarantee it'll always work, including in theory in the future, then it won't accept it.

If you want to assign a float value to T, you have to declare that this operation is possible, e.g. by adding f32: Into<T>, and using 180f32.into().

Kornel
  • 97,764
  • 37
  • 219
  • 309