如何解构到参考值,而不是参考借用?(How to destructure to reference

2019-09-28 06:39发布

如何改写接下来拥有这一切在同一行,在函数签名:

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>)) {
                                     ^~~~~

基本上,我需要的是模式,可以从借解构参考借来值。

Answer 1:

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&mut ref mut pixel解开从借位值之前ref mut使得pixel引用。

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



文章来源: How to destructure to reference to value instead of reference to borrow?
标签: rust