相关疑难解决方法(0)

如何在泛型函数中要求泛型类型实现Add,Sub,Mul或Div等操作?

我正在尝试在Rust中实现泛型函数,其中对参数的唯一要求是应该定义乘法运算.我正在尝试实现一个通用的"权力",但将使用更简单的cube功能来说明问题:

use std::ops::Mul;

fn cube<T: Mul>(x: T) -> T {
    x * x * x
}

fn main() {
    println!("5^3 = {}", cube(5));
}
Run Code Online (Sandbox Code Playgroud)

编译时我收到此错误:

error[E0369]: binary operation `*` cannot be applied to type `<T as std::ops::Mul>::Output`
 --> src/main.rs:4:5
  |
4 |     x * x * x
  |     ^^^^^^^^^
  |
  = note: an implementation of `std::ops::Mul` might be missing for `<T as std::ops::Mul>::Output`
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我选择了错误的特质吗?我该如何解决这个问题?

generics rust

21
推荐指数
2
解决办法
3128
查看次数

通用结构的构造函数中的"预期类型参数"错误

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

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,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这不编译:

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`)
Run Code Online (Sandbox Code Playgroud)

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

在Github做了一个可编辑的回购.

(我怀疑Rust的特征/特征:"预期'Foo <B>',发现'Foo <Foo2>'"是同一个问题,但我无法弄清楚如何将它应用到我的问题中.)

generics traits rust

19
推荐指数
1
解决办法
3643
查看次数

标签 统计

generics ×2

rust ×2

traits ×1