I am trying to implement a Directed Acyclic Graph in Rust, and have two structs defined like this:
struct ValueData {
val: BaseType,
children: Vec<Rc<RefCell<Value>>>,
name: &'static str,
}
pub struct Value(Rc<RefCell<ValueData>>);
Given a variable of type Value
, I want to be able to get its members like so:
impl Value {
fn name(&self) -> &'static str {
(*(self.0)).borrow().name
}
fn val(&self) -> BaseType {
(*(self.0)).borrow().val
}
fn children(&self) -> Vec<Rc<RefCell<Value>>> {
(*(self.0)).borrow().children
}
}
In this code example, the methods name
and val
compile properly, but children
doesn't with the following error:
error[E0507]: cannot move out of dereference of `Ref<'_, ValueData>`
--> src\grad.rs:61:9
|
61 | (*(self.0)).borrow().children
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `Vec<Rc<RefCell<Value>>>`, which does not implement the `Copy` trait
If I change it to the following:
fn children(&self) -> &Vec<Rc<RefCell<Value>>> {
&(*(self.0)).borrow().children
}
I then get an error:
error[E0515]: cannot return value referencing temporary value
--> src\grad.rs:61:9
|
61 | &(*(self.0)).borrow().children
| ^--------------------^^^^^^^^^
| ||
| |temporary value created here
| returns a value referencing data owned by the current function
Which makes it seems as if the Vector
is being cloned upon accessing it (if not, what is the "temporary value" that the compiler is complaining about?).
How do I get the pointer to the Vector
that already exists inside the ValueData
struct from the Value
struct? I don't want the vector to get copied, neither do I want to modify the vector or its contents -- all I want is a read-only reference so that I can print its contents recursively.
EDIT after getting marked duplicate: The answers to the linked question don't seem to be answering my question, since they are about acquiring a Ref<T>
while I want to be able to return &T
(that is, simply the pointer to the vector without any encapsulation). The only thing I can find in the leak
method, but it is marked nightly-only.