我试图获得一些更通用的东西但是没有尝试使用相关类型。给定的是Shape
特征和Renderer
类型,它会尝试为特定类型的形状返回Builder
。
形状
#[derive(Clone, Copy)]
pub struct Rectangle{
pub origin: Point,
pub height: usize,
pub width: usize,
}
pub trait Shape{
type Builder : ShapeBuilder;
}
impl Shape for Rectangle{
type Builder = RectangleBuilder;
}
助洗剂
pub trait ShapeBuilder{
type Renderer: ShapeRenderer;
fn set_origin() -> Self::Renderer;
}
pub struct RectangleBuilder;
impl ShapeBuilder for RectangleBuilder{
type Renderer = RectangleRenderer;
fn set_origin() -> Self::Renderer{
RectangleRenderer
}
}
渲染器
pub struct Renderer<'a>{
canvas:&'a mut Canvas
}
impl <'a>Renderer<'a>{
pub fn new(canvas:&'a mut Canvas) -> Renderer {
Renderer{
canvas: canvas
}
}
pub fn set_shape<T: Shape>(&self, shape: T) -> T::Builder{
// trying to return the specific builder through shape::Builder
// or something like that
}
}
我想要实现的是set_shape
方法会返回RectangleBuilder
,如果给定的shape
类型为Rectangle
答案 0 :(得分:2)
您需要在实例化新ShapeBuilder
的{{1}}特征中提供静态方法。静态方法只是一个没有Self
参数的方法。
您可以直接添加方法:
self
或聪明,并将pub trait ShapeBuilder: Sized {
type Renderer: ShapeRenderer;
fn new() -> Self;
fn set_origin() -> Self::Renderer;
}
定义为Default
的子广告。
ShareBuilder
然后,在pub trait ShapeBuilder: Default {
type Renderer: ShapeRenderer;
fn set_origin() -> Self::Renderer;
}
中,您可以实例化set_shape
:
ShapeBuilder