【问题标题】:Implement trait for base type (float)实现基本类型的特征(浮点数)
【发布时间】:2021-01-15 23:51:42
【问题描述】:

我想和戒指一起工作,所以我有一个特质 RingOps 并且我希望 float 成为其中的一部分。我认为float 实现了每个超类型,因此派生会很棒,但如果不是,该怎么做?

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

这是错误

    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}`

【问题讨论】:

    标签: rust numbers polymorphism traits parametric-polymorphism


    【解决方案1】:

    Rust 中没有 float 类型,您必须分别为 f32f64 实现它。一个例子:

    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

    【讨论】:

    • 酷!这让我比我想象的更进一步,f32 没有实现std::cmp::Eq 吗?
    • 啊 nvm 找到了,这是一个设计决策stackoverflow.com/questions/26958178/…
    • 值得注意的是,有一个crate 为浮点数(新类型的包装器)提供有用的EqOrdHash 实例。这些实现不符合 IEEE(因为 IEEE 未能满足所有这些特征的要求),但它们非常方便,而且在 IMO 中比 IEEE 定义更直观。
    猜你喜欢
    • 2019-12-08
    • 2018-04-11
    • 1970-01-01
    • 2014-09-01
    • 2021-07-02
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多