【发布时间】:2021-05-19 04:28:15
【问题描述】:
我在 Rust 中有以下代码:
pub struct RegExpFilter {
...
regexp_data: RefCell<Option<RegexpData>>,
...
}
struct RegexpData {
regexp: regex::Regex,
string: String
}
...
pub fn is_regexp_compiled(&self) -> bool {
self.regexp_data.borrow().is_some()
}
pub fn compile_regexp(&self) -> RegexpData {
...
}
fn regexp(&self) -> ®ex::Regex {
if !self.is_regexp_compiled() { // lazy computation that mutates the struct
self.regexp_data.replace(Some(self.compile_regexp()));
}
&self.regexp_data.borrow().as_ref().unwrap().regexp
}
pub fn matches(&self, location: &str) -> bool {
self.regexp().find(location)
}
正则表达式是惰性计算的,捕获&mut self我不想要,所以使用RefCell。
我收到以下消息:
&self.regexp_data.borrow().as_ref().unwrap().regexp
| ^-------------------------^^^^^^^^^^^^^^^^^^^^^^^^^
| ||
| |temporary value created here
| returns a value referencing data owned by the current function
编译器消息似乎很清楚:Ref 是由borrow() 临时创建并返回外部的。但是我相信Option (self.regexp_data) 归结构本身所有的RefCell 所有,所以在内部使用它应该没问题(因为函数不是pub)。
我也尝试了以下方法(但失败并显示相同的消息)
fn regexp(&self) -> impl Deref<Target = regex::Regex> + '_ {
if !self.is_regexp_compiled() {
self.regexp_data.replace(Some(self.compile_regexp()));
}
Ref::map(self.regexp_data.borrow(), |it| &it.unwrap().regexp)
}
我该如何解决?
【问题讨论】:
-
如果不保留
Ref<T>,就无法从RefCell<T>获得&T,RefCell如何知道何时允许borrow()和borrow_mut()。见this Q&A。
标签: rust ownership interior-mutability refcell