代码之家  ›  专栏  ›  技术社区  ›  Elf Sternberg

初始化Rust中的向量向量

  •  -1
  • Elf Sternberg  · 技术社区  · 7 年前

    我试图创建一个简单的多色mandelbrot生成器,扩展了O'Reilly的示例 crossbeam 板条箱,这是最后的目标。

    问题是我似乎无法将我的飞机矢量化。让我给你看看:

    pub struct Plane {
        bounds: (usize, usize),
        velocity: u8,
        region: Vec<u16>,
    }
    
    impl Plane {
        pub fn new(width: usize, height: usize, velocity: u8) -> Plane {
            Plane {
                bounds: (width, height),
                velocity: velocity,
                region: vec![0 as u16; width * height],
            }
        }
    }
    
    pub fn main() {
        // ... argument processing elided
        let width = 1000;
        let height = 1000;
        let velocity = 10;
        let planes = vec![Plane::new(width, height, velocity); 4]; // RGBa
    }
    

    当我试图建立这个,我得到:

    error[E0277]: the trait bound `Plane: std::clone::Clone` is not satisfied
      --> src/main.rs:23:18
       |
    23 |     let planes = vec![Plane::new(width, height, velocity); 4]; // RGBa
       |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Plane`
       |
       = note: required by `std::vec::from_elem`
       = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
    

    我试过创建一个巨大的平面,然后用 chunks_mut

    region: &' [u16]: this field does not implement 'Copy'
    

    Plane 对象,但是 vec![] 移动 它在某处,为了什么 Copy 复制 已经实施了吗?

    在一个平面上,即使在 here ),尽管在这种情况下,“一个巨大的平面”存在于父函数中,并且只将其切片传递给渲染器。

    有没有办法将平面数据数组移动到结构中以进行适当的封装?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Shepmaster Tim Diekmann    7 年前

    这个 Vec 结构宏 vec![val; n] Clone 因此它可以将示例元素复制到剩余的插槽中。所以,简单的解决办法是 Plane 实施

    #[derive(Clone)]
    pub struct Plane {
        bounds: (usize, usize),
        velocity: u8,
        region: Vec<u16>,
    }
    

    或者,您可以用不同的方式填充向量,而不依赖于实现的元素 克隆

    use std::iter;
    let planes: Vec<_> = iter::repeat_with(|| Plane::new(width, height, velocity))
        .take(4)
        .collect();
    
    推荐文章