Beginner Code review: How to implement a while loop with mutable reference to self?

For the simple case, where there is no intent of mutating the pointee, &'a T becomes Arc<T> within your structs.

So, where you used to create a value x of type T,

let x: T = ...;

You now need to wrap the value in an Arc:

let x: Arc<T> = Arc::new(...);

And now instead of giving a borrow of x, like &x, you give an Arc::clone(&x).
The code becomes slightly more cumbersome, but you get rid of references this way :slight_smile:

If you want to ever be able to mutate a value with this pattern, you need to wrap it in a RwLock (or a Mutex) before wrapping it in the Arc: Arc<RwLock<T>>.

Sharing it is still done using the .clone() from the outer Arc, but now reading the pointee requires calling .read().unwrap(), and read/writing to it requires .write().unwrap().


For a brief summary of these wrapper types, see this post

2 Likes