我有一个内部可变性的结构.
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();
}
Run Code Online (Sandbox Code Playgroud)
产生错误:
error[E0597]: borrowed value does not live long enough
--> …Run Code Online (Sandbox Code Playgroud) encapsulation contravariance mutability rust interior-mutability
我有一些设计问题,我想用安全的 Rust 来解决,但我一直无法找到可行的解决方案。我不能使用 aRefCell因为你不能得到 & 对数据的引用,只有Ref/ RefMut。
use std::cell::RefCell;
use std::rc::Rc;
struct LibraryStruct {}
impl LibraryStruct {
fn function(&self, _a: &TraitFromLibrary) {}
}
trait TraitFromLibrary {
fn trait_function(&self, library_struct: LibraryStruct);
}
// I don't want to copy this, bad performance
struct A {
// fields...
}
impl TraitFromLibrary for A {
fn trait_function(&self, library_struct: LibraryStruct) {
// custom A stuff
}
}
// B manipulates A's in data
struct B {
data: Vec<A>, …Run Code Online (Sandbox Code Playgroud) 有时我有一个struct包含在a 中的值RefCell,我想借用该值,但我不想让访问器函数的签名依赖于内部实现.为了使它工作,我需要返回引用Ref<T>而不是a &T.
例如,如果这是我的结构:
use std::cell::RefCell;
pub struct Outer<T> {
inner: RefCell<T>,
}
Run Code Online (Sandbox Code Playgroud)
我可以写一个这样的访问器:
use std::cell::Ref;
impl<T> Outer<T> {
fn get_inner_ref(&self) -> Ref<T> {
self.inner.borrow()
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用.我可以像这样使用它:
fn main() {
let outer = Outer { inner: RefCell::new(String::from("hi")) };
let inner: &str = &outer.get_inner_ref();
println!("inner value = {:?}", inner);
}
Run Code Online (Sandbox Code Playgroud)
但是,这会暴露Ref为公共API的一部分,这将使以后更改内部更加困难,而不会破坏向后兼容性.
如果我尝试更改签名以返回&T- &Ref<T>可以强制执行 - 那么我会遇到终生错误:
impl<T> Outer<T> {
fn get_inner_ref(&self) -> &T {
&self.inner.borrow()
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
error[E0597]: …Run Code Online (Sandbox Code Playgroud)