Rust 存储具有相同特征和不同输出类型的结构
我试图在Rust 存储具有相同特征和不同输出类型的结构,rust,Rust,我试图在Vec中存储具有共同特征的不同结构,因为您不知道Output,所以无法实际使用返回Output的函数,因为它们的大小都不一样,而且Rust不知道返回的是哪一个。解决此问题的最简单方法是使用枚举: 枚举阴影{ 元组2(TheirPoint,TheirPoint), 元组4(TheirPoint,TheirPoint,TheirPoint,TheirPoint) } 为他们的点显示他们的阴影{ 类型输出=阴影; fn投射阴影(自)->自::输出{ 阴影::Tuple2(一些点,一些其他点)
Vec中存储具有共同特征的不同结构,因为您不知道Output
,所以无法实际使用返回Output
的函数,因为它们的大小都不一样,而且Rust不知道返回的是哪一个。解决此问题的最简单方法是使用枚举:
枚举阴影{
元组2(TheirPoint,TheirPoint),
元组4(TheirPoint,TheirPoint,TheirPoint,TheirPoint)
}
为他们的点显示他们的阴影{
类型输出=阴影;
fn投射阴影(自)->自::输出{
阴影::Tuple2(一些点,一些其他点)
}
}
//等等
您甚至可以取消
输出
类型,只需强制trait中的返回值Shadow
。您将如何使用向量形状
?如果您不知道输出的类型
,则至少无法使用依赖该类型的任何函数。听起来不错!问题是,这里没有写“他们的”元素。有没有办法绘制这张地图?可能有父母的特征?匹配RPOINT::Output?您能更详细地说明您想要做什么吗?
fn main()
{
let p = TheirPoint ...
let l = TheirLine ...
let vec_shapes: Vec<Box<dyn TheirShadow>> = vec![Box::new(l), Box::new(p)];
}
impl TheirShadow for TheirPoint {
type Output = (TheirPoint, TheirPoint);
...
}
impl TheirShadow for TheirLine {
type Output = (TheirPoint, TheirPoint, TheirPoint, TheirPoint);
...
}
pub trait TheirShadow {
type Output;
...
}
error[E0191]: the value of the associated type `Output` (from trait `TheirShadow`) must be specified
--> src/main.rs:32:33
|
32 | let vec_shapes: Vec<Box<dyn TheirShadow>> = vec![Box::new(l), Box::new(p)];
| ^^^^^^^^^^^ help: specify the associated type: `TheirShadow<Output = Type>`
...
73 | type Output;
| ------------ `Output` defined here