这是我正在编写的解释器中提取的简单可重现错误。据我了解,由于RefCell具有足够的生命周期,我应该能够返回结构体字段的引用。然而,编译器告诉我不能返回当前函数拥有的值的引用,这让我感到困惑。
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Debug)]
enum Value {
Number,
String,
}
struct Object {
pub properties: HashMap<String, Value>,
}
impl Object {
pub fn get_property(&mut self, name: &str) -> Option<&mut Value> {
self.properties.get_mut(name)
}
}
fn get_property(global_object_rcc: Rc<RefCell<Object>>, name: &str) -> Option<&mut Value> {
// Rust cannot verify that this Rc isn't the last Rc that just got moved into this function?
global_object_rcc.borrow_mut().get_property(name)
}
fn main() {
// Construct global object
let mut global_object = Object {
properties: HashMap::new(),
};
// Give it a property
global_object
.properties
.insert("Test".to_owned(), Value::Number);
// Put it in a Rc<RefCell> (rcc) for sharing
let global_object_rcc = Rc::new(RefCell::new(global_object));
// Get a reference to its property, should be valid because the reference only needs to live
// as long as the global_object
let property = get_property(global_object_rcc, "Test");
dbg!(&property);
}
以下是我收到的错误信息:
error[E0515]: cannot return value referencing temporary value
--> src\main.rs:23:5
|
23 | global_object_rcc.borrow_mut().get_property(name)
| ------------------------------^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
global_object_rcc
是由get_property
函数拥有的,确切地说是因为它被移动到那里,当它超出范围时,先前称为global_object
的值将被丢弃。在某些情况下,Rust过于保守:这不是其中之一。您的代码存在使用后释放错误,编译器正在慷慨地向您发出警报,而不是让您调用UB。 - trent