MrMobster
MrMobster

Reputation: 1982

Make object expire given a state change in Rust

Is it possible in Rust to explicitly provide context on when an object expires? For instance, imagine a graph manipulation code that does something like this:

// borrow an edge from the graph
let edge : &Edge = graph.findEdge( ... );
// modify the edge
let new_edge : &Edge = graph.splitEdge(edge, vertex); 
// the old edge is invalid now, this should be an compiler error now!
edge.something

In general, is there some way to connect a lifetime of an object to a state or a state change?

Upvotes: 1

Views: 204

Answers (2)

notriddle
notriddle

Reputation: 668

There are two ways that can be done:

  1. find_edge can produce a &mut reference to the edge. Then split_edge will end up transferring the exclusive borrow into the reference it returns, making it inaccessible to the caller.

  2. find_edge can instead be take_edge. That is, it produces a non-copyable object that represents the edge. split_edge, of course, will consume it.

Upvotes: 0

wimh
wimh

Reputation: 15232

If you match your code to your comments, you will get an compiler error, although not at the position you want. Your current code is basically this. In this case split_edge looks like this:

fn split_edge(&self, edge: &Edge) -> &Edge {}

This does not allow you to change either the graph or the edge. So this function is not able to invalidate the edge. If you borrow self as mutable, you will get a compiler error, because you already borrow self as immutable:

fn split_edge(&mut self, edge: &Edge) -> &Edge {}
// error: cannot borrow `graph` as mutable because it is also borrowed as immutable [--explain E0502]

You would also run into errors if you borrow edge mutable instead.

If edge is not really invalidated, by you just want to avoid reusing it, just reuse the variable name edge instead of new_edge.

let edge : &Edge = graph.find_edge();
let edge : &Edge = graph.split_edge(edge);

Upvotes: 1

Related Questions