问题描述
以下代码无法编译,因为 MutRef 不是 Copy
.无法复制,因为 &'a mut i32
不是 Copy.有没有办法给 MutRef 类似的语义给 &'a mut i32
?
The following code fails to compile because MutRef is not Copy
. It can not be made copy because &'a mut i32
is not Copy. Is there any way give MutRef similar semantics to &'a mut i32
?
这样做的动机是能够将大量函数参数打包成一个结构体,以便它们可以作为一个组传递,而无需单独传递.
The motivation for this is being able to package up a large set of function parameters into a struct so that they can be passed as a group instead of needing to be passed individually.
struct MutRef<'a> {
v: &'a mut i32
}
fn wrapper_use(s: MutRef) {
}
fn raw_use(s: &mut i32) {
}
fn raw_ref() {
let mut s: i32 = 9;
let q = &mut s;
raw_use(q);
raw_use(q);
}
fn wrapper() {
let mut s: i32 = 9;
let q = MutRef{ v: &mut s };
wrapper_use(q);
wrapper_use(q);
}
推荐答案
没有
此功能的名称是隐式再借用",当您传递一个 &mut
引用时,编译器需要一个可能的 &mut
引用时会发生这种情况.不一样的人生.只有当实际类型和预期类型都是 &mut
引用时,编译器才会隐式地重新借用.它不适用于 generic参数 或包含 &mut
引用的结构.当前的 Rust 没有办法创建可以隐式重新借用的自定义类型.
The name for this feature is "implicit reborrowing" and it happens when you pass a &mut
reference where the compiler expects a &mut
reference of a possibly different lifetime. The compiler only implicitly reborrows when the actual type and the expected type are both &mut
references. It does not work with generic arguments or structs that contain &mut
references. There is no way in current Rust to make a custom type that can be implicitly reborrowed.
但是,您可以实现自己的方法来显式重新借用:
However, you can implement your own method to explicitly reborrow:
impl<'a> MutRef<'a> {
// equivalent to fn reborrow(&mut self) -> MutRef<'_>
fn reborrow<'b>(&'b mut self) -> MutRef<'b> {
MutRef {v: self.v}
}
}
fn wrapper() {
let mut s: i32 = 9;
let mut q = MutRef{ v: &mut s };
wrapper_use(q.reborrow()); // does not move q
wrapper_use(q); // moves q
}
另见
- 为什么这里没有移动可变引用?
- 类型推断和借用与所有权转让
这篇关于是否可以围绕 &mut 创建一个包装器,它的作用类似于 &mut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!