2017-08-10 81 views
1

我正在使用Piston和Sprite進行個人項目。該example code調用此方法:調用sprite :: Scene ::時出現類型不匹配:: draw

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>) 

那麼編譯器告訴我,該類型需要工具特點ImageSize所以我嘗試這樣的:

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>> 但我不想在該方法的簽名中寫入該類型。

我有兩個問題,那麼:

  1. 什麼是編譯器試圖告訴我嗎?
  2. 如何將場景傳遞給方法?

回答

1

draw的定義是:

impl<I: ImageSize> Scene<I> { 
    fn draw<B: Graphics<Texture = I>>(&self, t: Matrix2d, b: &mut B) 
} 

在也就是說,這大致對應於:

Scene是參數化與類型I實現ImageSize,函數draw將可用。 draw被參數與一類B必須與相關聯的Texture類型設置到相同類型I實施性狀Graphicsdraw函數是對Scene的引用的一種方法,並且需要兩個參數:t,一個Matrix2db,對B是什麼具體類型的可變引用。

爲了能夠撥打draw,您的功能需要有相同的限制,但是您不限制SGraphics::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() {}