我正在使用活塞和雪碧进行个人项目。示例代码调用此方法:
scene.draw(c.transform, g);
我正在尝试调用一种方法来绘制所有内容。 我第一次尝试:
draw<G: Graphics>(&self, c: &Context, g: &mut G, scene: &mut Scene)
然后编译器告诉我我需要给Scene
一个类型参数,所以我尝试了这个:
draw<G: Graphics, S>(&self, c: &Context, g: &mut G, scene: &mut Scene<S>)
然后编译器告诉我类型需要实现 traitImageSize
所以我尝试了这个:
draw<G: Graphics, S: ImageSize>(&self, c: &Context, g: &mut G, scene: &mut Scene<S>)
然后我得到这个错误:
error[E0271]: type mismatch resolving `<G as graphics::Graphics>::Texture == S`
--> src/game.rs:38:15
|
38 | scene.draw(c.transform, g);
| ^^^^ expected associated type, found type parameter
|
= note: expected type `<G as graphics::Graphics>::Texture`
found type `S`
我不明白编译器在这里想说什么。Scene
的完整类型sprite::Scene<piston_window::Texture<gfx_device_gl::Resources>>
但我不想在方法的签名中写下它。
那我有两个问题:
- 编译器想告诉我什么?
- 如何将场景传递给方法?
draw
的定义是:
impl<I: ImageSize> Scene<I> {
fn draw<B: Graphics<Texture = I>>(&self, t: Matrix2d, b: &mut B)
}
换句话说,这大致相当于:
当Scene
被参数化为实现ImageSize
的类型I
时,函数draw
将可用。draw
使用类型B
进行参数化,该类型必须实现特征Graphics
,并将关联的类型设置为与I
相同的类型Texture
。draw
函数是一个引用Scene
的方法,它接受另外两个参数:t
、Matrix2d
和b
,一个对任何具体类型的B
的可变引用。
为了能够调用draw
,您的函数需要具有相同的限制,但您并没有限制S
与Graphics::Texture
相同。这样做允许代码编译:
extern crate sprite;
extern crate graphics;
use graphics::{Graphics, ImageSize, Context};
use sprite::Scene;
struct X;
impl X {
fn draw<G>(&self, c: &Context, g: &mut G, scene: &mut Scene<G::Texture>)
where
G: Graphics,
{
scene.draw(c.transform, g);
}
}
fn main() {}