gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:34:25 27 4
gpt4 key购买 nike

我正在尝试创建一个简单的多色 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com