Yes
It is completely possible to use ownership and borrow funds to create your own security checks, and this is indeed a very interesting area of research that is open to us.
I would like to start with existing interesting things:
Back to your examples:
This is actually trivial.
In Rust, you can define how to capture your recipient:
impl Edge { fn split(self) { ... } // ^~~~ Look, no "&" }
Once the value has been consumed, it can no longer be used, so the next call is invalid.
I assume that you would like Edge maintain a link to the graph in order to prevent the graph from changing while you have an outstanding edge:
struct Edge<'a> { graph: &'a Graph,
will do the trick.
Moving:
It is impossible as it is.
To ensure that the order is maintained, the values must be related to each other, but here edge1 and edge2 are not.
A simple solution is to require edge1 act as the required proxy for the graph:
struct Edge<'a> { graph: &'a mut Graph,
Then we implement getter to temporarily access the chart:
impl<'a> Edge<'a> { fn get_graph<'me>(&'me mut edge) -> &'me mut Graph; }
And uses this result (named graph2 for convenience) to get edge2 .
This creates a chain of obligations:
- No one can touch
graph until edge1 dies - No one can touch
edge1 until graph2 dies - No one can touch
graph2 until edge2 dies
which ensures that objects are released in the correct order.
At compile time.
\ about /
Safety note. An important event at the beginning of the release of Rust was LeakPocalypse ( scoped_thread , which was declared bankrupt), which led Gankro (who wrote and pasted std::collections ) to write Pre-pooping Your Pants with Rust , which I urge you to read. In short, you should NEVER rely on a destructor executed to ensure security, because there is no guarantee that it (the object may be leaked, and then the thread will relax from panic). Pre-Pooping Your Pants is a strategy proposed by Gankro to get around this: put the element in a valid and safe (if it is semantically incorrect) state, do your stuff, restore real semantics when destroyed, and this is what the Drain iterator uses .