问题
I'm struggling to see how this transfers ownership. Here is my code:
let res = screenshot::take_screenshot(0);
let file = File::open("test.png").expect("Failed to open file");
let encoder = PNGEncoder::new(file);
encoder.encode(&res.into_raw(),
res.width(),
res.height(),
ColorType::RGBA(0)
);
screenshot::take_screenshot
is a function that returns an ImageBuffer<Rgba<u8>, Vec<u8>>
. Here is the compiler error I'm getting:
error[E0382]: use of moved value: `res`
--> src/main.rs:21:37
|
21 | encoder.encode(&res.into_raw(), res.width(), res.height(), ColorType::RGBA(0));
| --- ^^^ value used here after move
| |
| value moved here
|
= note: move occurs because `res` has type `image::ImageBuffer<image::Rgba<u8>, std::vec::Vec<u8>>`, which does not implement the `Copy` trait
error[E0382]: use of moved value: `res`
--> src/main.rs:21:50
|
21 | encoder.encode(&res.into_raw(), res.width(), res.height(), ColorType::RGBA(0));
| --- value moved here ^^^ value used here after move
|
= note: move occurs because `res` has type `image::ImageBuffer<image::Rgba<u8>, std::vec::Vec<u8>>`, which does not implement the `Copy` trait
I am trying to pass a slice, which I believe is a reference of the vector, is it not? This would imply ownership is not passed, and the vector isn't moved. I know I'm doing something wrong and it's likely something simple.
回答1:
This is simply an operator precedence issue: methods apply before the reference operator &
:
&(res.into_raw()) // This
(&res).into_raw() // Not this
Calling into_raw takes ownership and the value is gone.
You could do something like this:
let w = res.width();
let h = res.height();
let r = res.into_raw();
encoder.encode(&r, w, h, ColorType::RGBA(0));
It's likely there's something nicer, but you haven't provided a MCVE so it's hard to iterate on a solution. Blindly guessing from the docs, it looks like this should work:
extern crate image;
use image::{png::PNGEncoder, ColorType, ImageBuffer, Rgba};
use std::io;
fn repro<W: io::Write>(res: ImageBuffer<Rgba<u8>, Vec<u8>>, file: W) -> Result<(), io::Error> {
let encoder = PNGEncoder::new(file);
encoder.encode(&res, res.width(), res.height(), ColorType::RGBA(0))
}
fn main() {}
来源:https://stackoverflow.com/questions/49946620/why-does-value-into-something-still-result-in-a-moved-value