问题描述
如何在函数签名中重写以下内容以将其全部放在一行中:
How to rewrite what follows to have it all in one line, in function signature:
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>)) {
但这并不完全等同,因为我再也做不到了:
but that's not exact equivalent because I no longer can do:
*pixel = image::Luma([i as u8]);
在函数内部,当我有临时 tup
绑定时我可以这样做.
inside the function, that I could do when I had temporary tup
binding.
失败:
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>)) {
^~~~~
基本上我需要的是可以解构对借用值的引用的模式.
Basically what I need is pattern that can destructure reference to borrowed value from a borrow.
推荐答案
fn process(&mut (x,y, &mut ref mut pixel): &mut (u32,u32,&mut image::Luma<u8>)) {
这种模式 &mut (x,y, &mut ref mut pixel)
使 pixel
可变引用到借用值.
This pattern &mut (x,y, &mut ref mut pixel)
makes the pixel
mutable reference to borrowed value.
&mut
在 ref mut
生成 pixel 引用它.
&mut
in &mut ref mut pixel
unwraps the value from the borrow before ref mut
makes the pixel
reference to it.
我在这里查看后找到了这个解决方案:http://rustbyexample.com/flow_control/匹配/解构/destructure_pointers.html
I found this solution after looking here: http://rustbyexample.com/flow_control/match/destructuring/destructure_pointers.html
这篇关于如何解构以引用值而不是引用借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!