Generics &引用;预期类型参数“;泛型结构的构造函数中出错

Generics &引用;预期类型参数“;泛型结构的构造函数中出错,generics,rust,traits,Generics,Rust,Traits,我试图在结构中存储活塞纹理 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 {

我试图在结构中存储活塞纹理

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,
        }
    }
}
struct TextureFactory其中R:gfx::Resources{
块_纹理:Vec,
}
impl TextureFactory,其中R:gfx::Resources{
fn新(窗口:活塞窗口)->自{
让纹理=Rc::新建(gfx_纹理::纹理::从_路径(
&mut*window.factory.borrow_mut(),
“assets/element\u red\u square.png”,
翻转::无,&纹理设置::新建()
).unwrap());
让block_textures=Vec::new();
块_纹理。推(纹理);
织构学{
块纹理:块纹理,
}
}
}
这不会编译:

src/main.rs:37:9:39:10错误:不匹配的类型:
应为“TextureFactory”,
找到“TextureFactory”`
(应为类型参数,
找到枚举'gfx\U设备\U gl::资源')
gfx\u device\u gl::Resources
尽管如此(我认为这只是特定于设备的实现)。我实际上并不关心这是什么类型,但我需要知道,以便我可以将其存储在结构中

我发了一封信


(我怀疑是同一个问题,但我不知道如何将其应用于我的问题。)

这里是您错误的再现:

struct Foo<T> {
    val: T,
}

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

fn main() {}
尽管您可能希望选择一个比
new
更具体的名称,因为它看起来像是在尝试使结构通用。可能会有其他不同类型的构造函数

对于您的确切代码,您可能需要

impl TextureFactory<gfx_device_gl::Resources> { /* ... */ }
将来,您还可以使用
impl Trait
(又称存在主义类型):

#![特征(类型\u别名\u实施特征)]
结构Foo{
瓦尔:T,
}
输入SomeConcreteButOpaqueType=impl std::fmt::Display;
impl-Foo{
fn new()->Self{
Foo{val:true}
}
}
另见:


可能重复的或您可能使用的,以实现您的代码似乎涉及的多态性。谢谢!我没有意识到我可以在
impl
中“专门化”事物。
impl Foo<bool> {
    fn new() -> Self {
        Foo { val: true }
    }
}
impl TextureFactory<gfx_device_gl::Resources> { /* ... */ }
impl Foo<Box<dyn std::fmt::Display>> {
    fn new() -> Self {
        Foo { val: Box::new(true) }
    }
}
#![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 }
    }
}