将本地类型推断移到结构中

时间:2016-05-22 01:58:49

标签: rust type-inference

当本地定义类型并使用类型推断时,我有一些代码可以正常工作:

但问题是它在游戏的更新循环中加载字体。所以我想要做的是将glyph存储为Game结构的一部分并让它推断出类型

https://github.com/RustyRails/rustoid

即使Game结构具有正确的类型推断,代码也不会编译错误:

src/main.rs:89:13: 89:17 error: type mismatch resolving `<object::gfx_graphics::back_end::GfxGraphics<'_, gfx_device_gl::Resources, gfx_device_gl::command::CommandBuffer> as graphics::graphics::Graphics>::Texture == <T as graphics::character::CharacterCache>::Texture`:
 expected struct `gfx_texture::Texture`,
    found associated type [E0271]
src/main.rs:89             text(red, 32, "Hello World", &mut self.glyphs, transform, graphics)
                           ^~~~

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

你离得很近了。

我从未使用过活塞,但你在评论中留下了一个提示:

// let glyphs =
//        &mut Glyphs::new(font, factory).unwrap() as
//        &mut character::CharacterCache< Texture = Texture<gfx_device_gl::Resources> >
//    ;

您说glyphs实施character::CharacterCache,关联类型Texture必须为Texture<gfx_device_gl::Resources>

将此约束添加到on_draw可以解决问题:

fn on_draw<W, E>(&mut self, ren: RenderArgs, w: &mut PistonWindow<W>, e: &E)
    where W: Window, W::Event: GenericEvent, E: GenericEvent,
          T: character::CharacterCache< Texture = Texture<gfx_device_gl::Resources>>
{
    \\...
}

查看解决方案,错误更有意义:

<...>::Texture == <T as graphics::character::CharacterCache>::Texture
expected struct `gfx_texture::Texture`,
  found associated type [E0271]

预期的关联类型Texture是特定类型gfx_texture::Texture - 似乎Texture<gfx_device_gl::Resources>gfx_texture::Texture属于同一类型,我尝试使用{{1} }直接但无法执行此操作...),但gfx_texture::Texture可以包含T的任何关联类型,不一定是Texture。所以添加gfx_texture::Texture的限制 解决了这个问题。