我遇到以下代码错误:
use std::fs::File;
use std::io::{BufWriter, Write};
fn mandel_color(i: f32, mut writer: BufWriter<&File>) {
let ir = 16.0 * (i % 15.0);
let ig = 32.0 * (i % 7.0);
let ib = 8.0*(i % 31.0);
write!(&mut writer, "{} {} {}n", ir, ig, ib).expect("unable to write to file.");
}
fn mandel_iter(cx: f32, cy: f32) -> f32 {
let mut pair = (0.0, 0.0);
let mut count = 0.0;
while f32::sqrt(f32::powf(pair.0,2.0) + f32::powf(pair.1,2.0)) < 2.0 && count < 255.0 {
pair = ((f32::powf(pair.0,2.0) - f32::powf(pair.1,2.0) + cx), (2.0*pair.0*pair.1 + cy));
count += 1.0;
}
count
}
fn mandelbrot(width: i32, height: i32) {
let file = File::create("img/image.ppm").expect("unable to create image.ppm");
let mut writer = BufWriter::new(&file);
write!(&mut writer, "P3n{} {}n255n", width, height).expect("unable to write to file.");
for x in 0..width {
for j in 0..height {
let x_ish = ((x as f32 - width as f32 * 11.0/15.0) / (width as f32 /3.0)) as f32;
let y_ish = ((j as f32- height as f32 * 2.0) / (height as f32 * 3.0/10.0)) as f32;
// how do i fix the error with writer here?
mandel_color(mandel_iter(x_ish, y_ish), writer);
}
}
}
fn main() {
const IMAGE_WIDTH: i32 = 256;
const IMAGE_HEIGHT: i32 = 256;
mandelbrot(IMAGE_HEIGHT, IMAGE_WIDTH);
}
error[E0382]: use of moved value: `writer`
--> src/main.rs:32:53
|
25 | let mut writer = BufWriter::new(&file);
| ---------- move occurs because `writer` has type `BufWriter<&File>`, which does not implement the `Copy` trait
...
32 | mandel_color(mandel_iter(x_ish, y_ish), writer);
| ^^^^^^ value moved here, in previous iteration of loop
链接到操场
我尝试用#[derive(Copy)]
为Writer
设置一个结构,但BufWriter<&File>
无法实现Copy
特性。。。所以我不确定该如何处理这个案子。。。
如何处理循环中移动的值?特别是这个部分:
mandel_color(mandel_iter(x_ish, y_ish), writer);
原始代码将值移动到mandel_color()
,这不仅意味着调用者不能继续使用它,而且意味着mandel_color
将拥有编写器,因此一旦它写入单个三元组,并且writer
超出范围,就会关闭它。这种所有权转让当然不是有意的。
您可以防止所有权转移并修复";移动值";错误,因为没有移动值,在这种情况下,只是让mandel_color
接受对写入程序的引用:
fn mandel_color(i: f32, writer: &mut BufWriter<&File>) {
let ir = 16.0 * (i % 15.0);
let ig = 32.0 * (i % 7.0);
let ib = 8.0 * (i % 31.0);
write!(writer, "{} {} {}n", ir, ig, ib).expect("unable to write to file.");
}
呼叫站点调整为参考:
mandel_color(mandel_iter(x_ish, y_ish), &mut writer);
您还可以通过使mandel_color
与实现Write
特性的任何类型一起工作,使其更通用(而不会损失性能(。这样,您就不必拼写出确切的类型BufWriter<&File>
,并且您的代码将在写入网络套接字、标准输出、内存等的输出上保持不变:
fn mandel_color(i: f32, mut writer: impl Write) {
let ir = 16.0 * (i % 15.0);
let ig = 32.0 * (i % 7.0);
let ib = 8.0 * (i % 31.0);
write!(writer, "{} {} {}n", ir, ig, ib).expect("unable to write to file.");
}
游乐场