我需要处理来自包含不同数据类型的外部 rust 箱的枚举:
pub enum Variables {
Float(f32),
Double(f64)
}
我希望将其转换为我自己的通用数据 struct ,并将其包装在不同的 struct 中,以用元数据丰富它:
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MyWrapperVar<T> {
num: i8,
id: String,
var: MyVar<T>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MyVar<T> {
name: String,
value: T,
}
MyWrapperVar
个实例将被序列化并发送给不同的消费者.为了便于序列化,我创建了多个new
个函数:
impl MyVar<f32> {
fn new(name: &str, value: f32) -> Self {
Self {
name: name.to_string(),
value,
}
}
}
impl MyVar<f64> {
fn new(name: &str, value: f64) -> Self {
Self {
name: name.to_string(),
value,
}
}
}
impl<T> MyWrapperVar<T> {
fn new(
num: i8,
id: &str,
variable_name: &str,
variable_value: T,
) -> MyWrapperVar<T> {
Self {
num,
id: id.to_string(),
var: MyVar::<T>::new(variable_name, variable_value),
}
}
}
我的印象是,我可以简单地匹配Variables
,然后调用我的通用MyWrapperVar::new
函数:
fn main() {
let var1 = Variables::Float(0.1);
match var1 {
Variables::Float(v) => {
let bla = MyWrapperVar::new(0, "bla", "var1", v);
}
Variables::Double(v) => {
let bla = MyWrapperVar::new(0, "bla", "var1", v);
}
}
}
但是,这似乎不起作用,因为我收到以下错误:
error[E0599]: no function or associated item named `new` found for struct `MyVar<T>` in the current scope
--> src/main.rs:42:30
|
9 | pub struct MyVar<T> {
| ------------------- function or associated item `new` not found for this struct
...
42 | var: MyVar::<T>::new(variable_name, variable_value),
| ^^^ function or associated item not found in `MyVar<T>`
|
= note: the function or associated item was found for
- `MyVar<f32>`
- `MyVar<f64>`
For more information about this error, try `rustc --explain E0599`.
请参见Rust Playground以获得MRE.