【发布时间】:2016-09-10 08:22:39
【问题描述】:
我即将给出一个 trait 作为参数,通过一个名为 new 的构造方法来存储它。
结构类型的特征在此处作为参数给出:
渲染器.rs
use super::shapes::Shape;
pub struct Renderer;
impl Renderer{
pub fn set_shape<T : Shape>(&self, shape: T) -> T::Builder{
T::Builder::new(shape)
}
}
那么会调用关联类型指定的Builder的构造函数
shapebuilder.rs
use super::shapes::Shape;
use super::shapes::Rectangle;
pub trait ShapeBuilder{
fn new<T:Shape>(shape: T) -> Self;
}
pub struct RectangleBuilder{
shape: Shape<Builder=RectangleBuilder>
}
impl ShapeBuilder for RectangleBuilder{
fn new<T:Shape>(shape: T) -> Self{
RectangleBuilder{
shape: shape as Rectangle
}
}
}
此时我已经想指出编译器输出了
编译器输出
error[E0277]: the trait bound `shapes::Shape<Builder=shapebuilder::RectangleBuilder> + 'static: std::marker::Sized` is not satisfied
--> shapes.rs:14:6
|
14 | impl Shape for Rectangle{
| ^^^^^
|
= note: `shapes::Shape<Builder=shapebuilder::RectangleBuilder> + 'static` does not have a constant size known at compile-time
= note: required because it appears within the type `shapebuilder::RectangleBuilder`
= note: required by `shapes::Shape`
error: aborting due to previous error
我在 SO 上发现了类似的问题,其中介绍了有关拳击的一些信息。我尝试将每个参数类型装箱以解决问题。像这样装箱shape: Box<T>。没有成功。我需要装箱吗?我理解编译器无法解决特征大小的问题,因为特定/具体的结构类型可能具有不同的大小,具体取决于它们的字段/属性。我仍然无法找到解决方案。希望它是微不足道的。
为了完整性而列出的未涉及的模块(我认为)
shapes.rs
use super::shapebuilder::ShapeBuilder;
use super::shapebuilder::RectangleBuilder;
pub trait Shape{
type Builder: ShapeBuilder;
}
#[derive(Clone, Copy)]
pub struct Rectangle{
pub height: usize,
pub width: usize,
}
impl Shape for Rectangle{
type Builder = RectangleBuilder;
}
lib.rs
pub mod renderer;
mod shapes;
mod shapebuilder;
【问题讨论】:
-
这是你能做到的最小的例子吗?尝试找出具体问题,这将使您和我们都更清楚。
-
renderer.rs和shapebuilder.rs已经尽可能小,并且是唯一的重要信息。以标题 NOT involed modules... 开头的内容 - 正如我所提到的 - 只是为了完整性,因为人们在另一个问题上要求所有模块自己编译和测试。请务必先阅读所有标题。 -
我认为您没有正确理解我的观点 - 您当前的代码示例不是最小的并且包含从您的其他文件中导入的内容。为了使您的问题更清楚,您应该找到导致问题的代码部分,并完全摆脱其余部分,以制作一个仍然存在相同问题的更简单的示例。就目前而言,我需要将您的所有文件和目录结构复制到一个项目中,以重现您的问题,如果您进一步隔离问题,则没有必要这样做。
-
嗯,你是对的 - 我正在花时间用一个更有针对性的例子来更新这个问题。
-
现在让代码更简单了——我更喜欢这种方式,谢谢
标签: memory constructor rust traits