为什么 `&value.into_something()` 仍然会导致移动的值? [英] Why does `&value.into_something()` still result in a moved value?

查看:43
本文介绍了为什么 `&value.into_something()` 仍然会导致移动的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解这是如何转移所有权的.这是我的代码:

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 是一个返回 ImageBuffer, Vec> 的函数.这是我得到的编译器错误:

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.

推荐答案

这只是一个运算符优先级问题:方法在引用运算符 & 之前应用:

This is simply an operator precedence issue: methods apply before the reference operator &:

&(res.into_raw()) // This
(&res).into_raw() // Not this

调用 into_raw 取得所有权,价值就消失了.

Calling into_raw takes ownership and the value is gone.

你可以这样做:

let w = res.width();
let h = res.height();
let r = res.into_raw();
encoder.encode(&r, w, h, ColorType::RGBA(0));

可能有更好的方法,但您尚未提供 MCVE,因此很难迭代解决方案.从文档中盲目猜测,看起来这应该可行:

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() {}

这篇关于为什么 `&amp;value.into_something()` 仍然会导致移动的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆