Implement trait for base type (float)

Viewed 371

I want to work with rings, so I have a trait RingOps and I want float to be a part of it. I think float implements each supertype so deriving would be great, but if not, how to do this?

trait RingOps: Add<Output=Self> + Mul<Output=Self> + Eq + Debug
    where Self: std::marker::Sized {}
  
impl RingOps for float {}

Here's the error

    error[E0412]: cannot find type `float` in this scope
 --> src/main.rs:8:18
  |
8 | impl RingOps for float {}
  |                  ^^^^^ not found in this scope

error[E0277]: the trait bound `{float}: RingOps` is not satisfied
  --> src/main.rs:44:32
   |
13 |     Input(&'a str, T),
   |     ----------------- required by `Circuit::Input`
...
44 |         Box::new(Circuit::Input("a", 2.0)),
   |                                      ^^^ the trait `RingOps` is not implemented for `{float}`
1 Answers

There's no float type in Rust, you have to implement this for f32 and f64 respectively. An example:

use std::fmt::Display;

trait Trait: Display {
    fn print(&self) {
        println!("i am {}", self);
    }
}

impl Trait for f32 {}
impl Trait for f64 {}

fn main() {
    1.5_f32.print(); // prints "i am 1.5"
    1.5_f64.print(); // prints "i am 1.5"
}

playground

Related