【发布时间】:2020-05-01 02:58:15
【问题描述】:
我想要一个接受多种数字类型的特征对象的方法,所有这些都将转换为f64。以下内容无法编译,因为 NumCast 实现了 Sized 特征:
use num_traits::NumCast;
pub trait Grapher {
fn add(&mut self, key: &str, number: &dyn NumCast);
fn show(&self);
}
此类方法的通用版本禁用 Grapher 以创建对象:
fn agregar<T: NumCast>(&mut self, key: &str, number: &T);
我的解决方案是创建另一个特征:
pub trait F64Convertible {
fn convert(&self) -> f64;
}
impl F64Convertible for i32 {
fn convert(&self) -> f64 {
*self as f64
}
}
impl F64Convertible for u8 {
fn convert(&self) -> f64 {
*self as f64
}
}
// same for many numeric types...
// use the trait:
pub trait Grapher {
fn add(&mut self, key: &str, number: &dyn F64Convertible);
fn show(&self);
}
我想避免在我的代码中重复转换函数,可能会利用 NumCast 或类似的特征。
【问题讨论】:
-
在调用函数转换变量时接受一种类型然后使用
as有什么问题? -
没有错,更多的是理论问题。调用者可能有几种类型的数值。我想接受一系列类型(例如那些实现 NumCast 的类型),避免调用者的转换。