在Rust中初始化向量向量

问题描述 投票:-1回答:1

我正在尝试创建一个简单的多色mandelbrot生成器,扩展了O'Reilly的Programming Rust中的示例。我们的想法是创建具有略微不同的逃逸速度的三个不同的“灰色”平面,然后将它们合并为RGB样式的彩色图像。主要思想是每个平面都是独立的,因此每个平面都可以使用crossbeam crate通过单独的线程进行处理,这是最终目标。

问题是我似乎无法对我的飞机进行矢量化。让我演示给你看:

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,但在其中我只想移动数组的句柄,而不是数据吧?那只是一个位图本身,它不应该已经实现了Copy吗?

这在单个平面上工作正常,即使该平面被切成多个区域进行多核处理(参见示例here),尽管在这种情况下,“一个巨大的平面”存在于父函数中并且只有它的切片被切换到渲染器。

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

vector syntax rust initialization
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.