r/rust•
Cyclip

How would I return a borrowed variable?

I'm trying to make a simple function with 2 statements both of which mutate 2 variables to link them together

impl<'a> Node<'a> {
    // Add a child to this node
    pub fn add_child(&'a mut self, child: &'a mut Node<'a>) {
        self.children.push(child); // Add child to Vec<&'a Node<'a>>
        child.parent = Some(self); // Set child's parent to Option<&'a Node<'a>>
    }
}

What I understand is that a reference to child is pushed onto self.children at line 4, and there can be any number of references because it is an immutable reference.

Then child is mutably borrowed at line 5 and its parent field is assigned a value, but the rust compiler gives an error saying that I can't assign to child.parent because it's borrowed at line 4.

Is there any way to drop the borrow after line 4 or do I need to restructure the function?

Posted Jun 25, 2021, 10:02 AM UTC

128
SkiFire13•

There's a fundamental problem with what you're trying to do, which is trying to create a self referential struct, which is not possible in safe rust. If this was possible then node.children[0].parent.unwrap() would get you a shared borrow of node while also leaving the rest of node not borrowed; this way you can have a mutable reference and a shared reference to the same data at the same time, and this is UB.

A big red flag for this cases should be the &'a mut self. You almost never want a &'a mut Node<'a>. This is saying that a Node<'a> can't live more than 'a because otherwise the references it contains would become invalid, but at the same time you want a reference to it that last at least 'a. This is a contradiction, and even if it compiles it would be unusable (usually you either get an error when you call that function or you can't touch the struct anymore after calling it).

If you're trying to create some sort of tree/graph I would suggest you to store the nodes in a vec and use indexes instead of pointers to point to the parent/childrens. The petgraph crate also helps with this approach.

21
CyclipOP•

Ohh thank you that makes more sense, I'll try the last approach :p

3
schungx•

Welcome to the borrow checker. Rust is designed to stop you from doing what you intend to do, because that's a way to cause memory bugs.

Your choice is either to not use Rust, or rewrite the logic into something that passes the borrow checker. And once you do that, your program will no longer have any memory bugs.

Short answer: You cannot build a doubly-linked list naively in Rust. Rust stops you. You can check out the great intro at:

https://rust-unofficial.github.io/too-many-lists/

6
SlipperyFrob•

The borrow is moved into self.children, where you want it to remain. If you could somehow drop it, self.children would be useless.

More to the point, borrows aren't universal replacements for pointers or references à la C++ (even though folks here call them references). In particular you generally can't have one object that has a borrow of another object that in turn borrows the first object (or otherwise have cyclic borrow-fests), because then you can't drop or move either object without invalidating the borrow held by the other.

Instead you need to walk the compiler through how you're going to manage the lifecycle of your nodes, and/or defer some of the memory safety checks to runtime. For trees, Rc/Arc with Weak work OK. Other options involve arena allocators, the slotmap crate, or the petgraph crate.

2
CyclipOP•

What's Rc/Arc?

1
ssokolow•

Rc<T> and Arc<T> are single-thread and threadsafe reference-counted smart pointers, respectively. (The "A" indicates that it uses atomic primitives to manage the reference count.)

They allow multiple ownership with the lifetime determined at runtime.

5

Referenced counted and atomic referenced counted pointer types, the popular 'alternatives' to garbage collection in languages without it that check the number of references at runtime and only run destructors when they count down to zero.

Rust separates them into two because sometimes you want RC in single threaded situations because it's hard-to-impossible to express a convoluted object graph/algorthim with pure rust lifetimes, but you don't want to pay the mutex tax of the atomic.

Weak is yet another of those runtime checked pointer types but it solves the situation where you don't want a particular reference to prevent the destructor running. I don't know exactly how it is prevented in rust after getting it on the callsite, but in GC languages you usually do it by at callsite storing the underlying object in a local variable and testing for 'none' (nullness) and depending on the GC noticing that live variable. It serves to break up object graph cycles that would otherwise 'leak' the memory at the small, small cost of having a section(s) of the code that uses that 'potentially none' reference have a predictable extra bailout code path.

This is obviously different in rust because it has no gc to prevent the destructor running but it's probably some kind of detail like a counter increasing in the reference type and saying 'no' to the destructor while it's being used or something. Probably by combining it with RC in fact.

2
SlipperyFrob•

the mutex tax of the atomic

Just to clarify: mutexes are typically an OS-offered feature (in particular std::sync::Mutex is the OS mutex), while rust's atomics are implemented with the synchronization instructions native to the hardware platform. The latter are a bit faster than what you would get by using an OS mutex to implement atomics. The tax you pay with an Arc over Rc is that those synchronization instructions are nevertheless slower than the simple integer increment/decrement in Rc.

And yes, Weak is implemented by keeping a count of both strong and weak references. Once the strong count hits zero, the object is dropped (and all weak derefs return None), but the metadata is kept around until the weak count also hits zero.

3