rust - 实现基本类型的特征(浮点数)
问题描述
我想和戒指一起工作,所以我有一个特质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}`
解决方案
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"
}
推荐阅读
- python - 从多维列表中删除重复项(python)
- python - MS Graph/assignLicense:预期原始“空”值
- python - 使用 += 将变量添加到变量
- python - 通过 refresh_from_db() 使用不同的管理器
- amazon-web-services - 与 Amazon ElastiCache Redis 集群的 redis-cli 连接挂起
- botframework - MS Teams 中的 OAuthCard 和幻数
- python - 傅里叶滤波,回到图像
- angularjs - 带有组件 $pristine 的 AngularJS 在设置名称时返回未定义
- ios - AS3 将文件保存在 iOS 上可访问的位置
- javascript - 如何在 vue.js 中进行条件异步操作