泛型结构的构造函数中出现“预期类型参数”错误

2023-12-06

我正在尝试将活塞纹理存储在结构中。

struct TextureFactory<R> where R: gfx::Resources {
    block_textures: Vec<Rc<Texture<R>>>,
}

impl<R> TextureFactory<R> where R: gfx::Resources  {
    fn new(window: PistonWindow) -> Self {
        let texture = Rc::new(gfx_texture::Texture::from_path(
            &mut *window.factory.borrow_mut(),
            "assets/element_red_square.png",
            Flip::None, &TextureSettings::new()
        ).unwrap());
        let block_textures = Vec::new();
        block_textures.push(texture);

        TextureFactory {
            block_textures: block_textures,
        }
    }
}

这不会编译:

src/main.rs:37:9: 39:10 error: mismatched types:
 expected `TextureFactory<R>`,
    found `TextureFactory<gfx_device_gl::Resources>`
(expected type parameter,
    found enum `gfx_device_gl::Resources`)

gfx_device_gl::Resources 实施gfx::Resources不过(我认为这只是设备特定的实现。)我实际上并不关心这是什么类型,但我需要知道,以便可以将其存储在结构中。

我制造了一个Github 上的可编译存储库.

(我猜测Rust 泛型/特征:“预期为 'Foo',发现为 'Foo'”是同一个问题,但我不知道如何将其应用于我的问题。)


这是您的错误的重现:

struct Foo<T> {
    val: T,
}

impl<T> Foo<T> {
    fn new() -> Self {
        Foo { val: true }
    }
}

fn main() {}

问题的出现是因为你试图对编译器撒谎。这段代码:

impl<T> Foo<T> {
    fn new() -> Self {
        /* ... */
    }
}

说“无论怎样T the caller选择,我将创建一个Foo与该类型“。然后你的实际实现选择一个具体类型— 在示例中,bool。无法保证T is a bool。请注意,您的new函数甚至不接受任何类型的参数T,这是高度可疑的,因为 99% 的情况下调用者都是这样选择具体类型的。

正确的说法是

impl Foo<bool> {
    fn new() -> Self {
        Foo { val: true }
    }
}

尽管您可能想选择一个比new,因为看起来您正在尝试使您的结构变得通用。想必会有other具有不同类型的构造函数。

对于您的确切代码,您可能想要类似的东西

impl TextureFactory<gfx_device_gl::Resources> { /* ... */ }

另一种可能的解决方案是从结构中删除泛型类型参数。如果你只用一个来构建它gfx_device_gl::Resources,那么就没有理由使其通用。

在其他情况下,您可能尝试返回实现特征的类型。为此,您可以使用盒装特征对象:

impl Foo<Box<dyn std::fmt::Display>> {
    fn new() -> Self {
        Foo { val: Box::new(true) }
    }
}

将来,您也许还可以使用impl Trait(又名存在类型):

#![feature(type_alias_impl_trait)]

struct Foo<T> {
    val: T,
}

type SomeConcreteButOpaqueType = impl std::fmt::Display;

impl Foo<SomeConcreteButOpaqueType> {
    fn new() -> Self {
        Foo { val: true }
    }
}

也可以看看:

  • 返回迭代器(或任何其他特征)的正确方法是什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

泛型结构的构造函数中出现“预期类型参数”错误 的相关文章

随机推荐