此问题在此处已有答案:
Can a function return different types depending on conditional statements in the function?(1个答案)
昨天就关门了。
这篇文章是昨天编辑并提交审查的。
如果我想让一个泛型函数返回一个泛型结构体,它的类型是根据某个参数定义的,那么我该如何实现呢?
我有类似以下的东西:
- 其他板条箱的结构(超出我的控制范围)
struct Foo{
data_type: String,
data_int32: Vec<i32>,
data_int64: Vec<i64>,
data_int32: Vec<f32>,
data_int64: Vec<f64>,
data_raw: Vec<u8>
}
字符串
- 我的结构
struct A<T>{
data: Vec<T>,
}
impl<T> A<T>{
fn new(data: T) -> Self{
A{
data: data
}
}
}
impl<T> From<Foo> for A<T>{
fn from(foo: Foo) -> Self{
match foo.data_type{
"i32" => A::new(foo.data_i32),
"i64" => A::new(foo.data_i64),
"f32" => A::new(foo.data_f32),
"f64" => A::new(foo.data_f64),
_ => A::new(foo.data_raw)
}
}
}
型
这返回我以下错误:expected struct A<T> found struct A<i32>
或expected struct A<T> found struct A<f32>
ecc.
我尝试了各种不同的解决方案,如限制通用值与T: From::<...>
,但没有任何工作,我总是回落到这种错误。
我该如何解决此问题?
1条答案
按热度按时间20jt8wwn1#
你不能。这个调用的结果类型是什么?
字符串