在Rust中初始化向量的向量

时间:2018-08-29 16:28:59

标签: vector syntax rust initialization

我正在尝试创建一个简单的多色mandelbrot生成器,以扩展O'Reilly的 Programming Rust 中的示例。这个想法是创建三个不同的灰度图“平面”,其逃逸速度略有不同,然后将它们合并为RGB样式的色图图像。主要思想是每个平面都是独立的,因此可以使用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![]宏想要将其移动到某个地方,为此{ 1}}必须实现,但是在那我只想移动数组的句柄,而不是数据,对吗?那本身只是一个位图,是否不应该已经实现Copy

即使将 平面切成用于多核处理的区域(参见示例here),该功能也可以在单个平面上正常工作,尽管在这种情况下,“一个巨大的平面”位于父函数中,并且只有其中一部分会传递给渲染器。

是否有一种方法可以将平面数据数组移入结构以进行正确封装?

1 个答案:

答案 0 :(得分:4)

Vec构造宏vec![val; n]要求元素类型实现Clone,以便可以将示例元素复制到其余插槽中。因此,简单的解决方法是使Plane实现Clone

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

或者,您可以用另一种方式填充向量,而不依赖于实现Clone的元素。例如:

use std::iter;
let planes: Vec<_> = iter::repeat_with(|| Plane::new(width, height, velocity))
    .take(4)
    .collect();
相关问题