【问题标题】:Moving local type inference out to a struct将本地类型推断移出结构
【发布时间】:2023-03-05 20:00:01
【问题描述】:

我有一些代码在本地定义类型并使用类型推断时绝对正确:

但问题是它在游戏的更新循环中加载字体。所以我想做的是将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)
                           ^~~~

我在这里错过了什么?

【问题讨论】:

  • 请生成MCVE 并在此处发布该代码。作为理解问题的主要方式的非现场资源链接不适用于 Stack Overflow,但您可以包含该链接作为进一步的信息。
  • @heptic 你能提供一个 MCVE 吗?

标签: rust type-inference


【解决方案1】:

你已经接近了。

我从来没有用过活塞,但你在评论中留下了小费:

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

您是说glyphs 实现了character::CharacterCache 并且关联类型Texture 必须是Texture&lt;gfx_device_gl::Resources&gt;

将此约束添加到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&lt;gfx_device_gl::Resources&gt;gfx_texture::Texture 是同一类型,我尝试直接使用gfx_texture::Texture 但无法这样做.. .),但T 可以有Texture 的任何关联类型,不一定是gfx_texture::Texture。所以添加T::Texture = Texture&lt;gfx_device_gl::Resources&gt;的限制 解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多