如何进行结构化以引用价值而不是借用借款?

时间:2016-06-20 15:41:37

标签: rust

如何在函数签名中重写以下内容以将其全部放在一行:

fn process(tup: &mut (u32,u32,&mut image::Luma<u8>)) {
  let &mut (x,y, _) = tup;
  let ref mut pixel = *tup.2;

我得到了:

fn process(&mut (x,y, ref mut pixel): &mut (u32,u32,&mut image::Luma<u8>)) {

但这不完全等同,因为我再也无法做到了:

*pixel = image::Luma([i as u8]);

在函数内部,当我有临时tup绑定时,我可以做。

失败:

src\main.rs:43:14: 43:36 note: expected type `&mut image::Luma<u8>`
src\main.rs:43:14: 43:36 note:    found type `image::Luma<u8>`

我也尝试过:

process(&mut (x, y, pixel): &mut (u32,u32,&mut image::Luma<u8>))

但是失败了:

src\main.rs:23:12: 23:29 error: cannot move out of borrowed content [E0507]
src\main.rs:23 fn process(&mut (x,y, pixel): &mut (u32,u32,&mut image::Luma<u8>)) {
                          ^~~~~~~~~~~~~~~~~
src\main.rs:23 fn process(&mut (x,y, pixel): &mut (u32,u32,&mut image::Luma<u8>)) {
                                     ^~~~~

基本上我需要的是能够从借入中借鉴借入价值的结构模式。

1 个答案:

答案 0 :(得分:0)

fn process(&mut (x,y, &mut ref mut pixel): &mut (u32,u32,&mut image::Luma<u8>)) {

此模式&mut (x,y, &mut ref mut pixel)使pixel可变参考借用值。

&mut中的{p> &mut ref mut pixelref mut对其进行pixel引用之前解除借用的值。

我在这里看到后找到了这个解决方案:http://rustbyexample.com/flow_control/match/destructuring/destructure_pointers.html