如何在不破坏封装的情况下返回对RefCell内部内容的引用? [英] How do I return a reference to something inside a RefCell without breaking encapsulation?
问题描述
我有一个具有内部可变性的结构.
I have a struct that has inner mutability.
use std::cell::RefCell;
struct MutableInterior {
hide_me: i32,
vec: Vec<i32>,
}
struct Foo {
//although not used in this particular snippet,
//the motivating problem uses interior mutability
//via RefCell.
interior: RefCell<MutableInterior>,
}
impl Foo {
pub fn get_items(&self) -> &Vec<i32> {
&self.interior.borrow().vec
}
}
fn main() {
let f = Foo {
interior: RefCell::new(MutableInterior {
vec: Vec::new(),
hide_me: 2,
}),
};
let borrowed_f = &f;
let items = borrowed_f.get_items();
}
产生错误:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:16:10
|
16 | &self.interior.borrow().vec
| ^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
17 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 15:5...
--> src/main.rs:15:5
|
15 | / pub fn get_items(&self) -> &Vec<i32> {
16 | | &self.interior.borrow().vec
17 | | }
| |_____^
问题是我在Foo
上没有返回借用的vec
的函数,因为借用的vec
仅在Ref
的生存期内有效,但是Ref
立即超出范围.
The problem is that I can't have a function on Foo
that returns a borrowed vec
, because the borrowed vec
is only valid for the lifetime of the Ref
, but the Ref
goes out of scope immediately.
我认为Ref
必须坚持因为 :
RefCell<T>
使用Rust的生存期来实现动态借用",这一过程使人们可以要求对内部值进行临时,排他,可变的访问.RefCell<T>
的借用是在运行时"进行跟踪的,这与Rust的本机引用类型不同,后者在编译时是完全静态跟踪的.因为RefCell<T>
借位是动态的,所以可以尝试借入已经可变借值的值;当这种情况发生时,会导致任务出现紧急情况.
RefCell<T>
uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can claim temporary, exclusive, mutable access to the inner value. Borrows forRefCell<T>
s are tracked 'at runtime', unlike Rust's native reference types which are entirely tracked statically, at compile time. BecauseRefCell<T>
borrows are dynamic it is possible to attempt to borrow a value that is already mutably borrowed; when this happens it results in task panic.
现在,我可以改写这样的函数来返回整个内部空间:
Now I could instead write a function like this that returns the entire interior:
pub fn get_mutable_interior(&self) -> std::cell::Ref<MutableInterior>;
但是,这可能会将真正是私有实现详细信息的字段(在本示例中为MutableInterior.hide_me
)暴露给Foo
.
However this potentially exposes fields (MutableInterior.hide_me
in this example) that are really private implementation details to Foo
.
理想情况下,我只想公开vec
本身,并可能带有实现动态借用行为的保护措施.这样,呼叫者就不必了解hide_me
.
Ideally I just want to expose the vec
itself, potentially with a guard to implement the dynamic borrowing behavior. Then callers do not have to find out about hide_me
.
推荐答案
您可以创建类似于RefCell::borrow()
返回的Ref<'a,T>
防护的新结构,以包装此Ref
并避免其外出范围,例如:
You can create a new struct similar to the Ref<'a,T>
guard returned by RefCell::borrow()
, in order to wrap this Ref
and avoid having it going out of scope, like this:
use std::cell::Ref;
struct FooGuard<'a> {
guard: Ref<'a, MutableInterior>,
}
然后,您可以为其实现Deref
特征,以便可以像使用&Vec<i32>
一样使用它:
then, you can implement the Deref
trait for it, so that it can be used as if it was a &Vec<i32>
:
use std::ops::Deref;
impl<'b> Deref for FooGuard<'b> {
type Target = Vec<i32>;
fn deref(&self) -> &Vec<i32> {
&self.guard.vec
}
}
之后,更新您的get_items()
方法以返回FooGuard
实例:
after that, update your get_items()
method to return a FooGuard
instance:
impl Foo {
pub fn get_items(&self) -> FooGuard {
FooGuard {
guard: self.interior.borrow(),
}
}
}
和Deref
发挥了魔力:
fn main() {
let f = Foo {
interior: RefCell::new(MutableInterior {
vec: Vec::new(),
hide_me: 2,
}),
};
let borrowed_f = &f;
let items = borrowed_f.get_items();
let v: &Vec<i32> = &items;
}
这篇关于如何在不破坏封装的情况下返回对RefCell内部内容的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!