vector - 在 Rust 中初始化向量的向量

标签 vector syntax rust initialization

我正在尝试创建一个简单的多色 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),尽管在那种情况下“一个巨大的平面”仍然存在在父函数中,只有它的一部分被传递给渲染器。

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

最佳答案

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();

关于vector - 在 Rust 中初始化向量的向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52082169/

相关文章:

rust生命周期问题,为什么第一次调用没有编译错误?

rust - 生命周期必须对静态生命周期有效,以便类型兼容

c++ - 在cpp中调整 vector 大小

reference - 有没有办法返回对函数中创建的变量的引用?

c++ - 从存储在集合中的数字计算 vector 中的 int?

kotlin - 两个值之间不同值 '===' 的运算符 'name' 的不同结果

syntax - 为什么我不能用新行的每个分隔符和字段更新记录?

r - 将权重传递给函数内的 lm 和其他人

C++将值添加到一种矩阵

c++ - C++中不同派生类的高效容器