Why does `&value.into_something()` still result in a moved value?

人盡茶涼 提交于 2021-02-20 02:54:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!