How to do it...

Let's create a test to establish the best way to share mutable ownership in just a few steps:

  1. Let's create a couple of new functions inside the testing module:
    use std::cell::{Cell, RefCell};    use std::borrow::Cow;    use std::ptr::eq;    fn min_sum_cow(min: i32, v: &mut Cow<[i32]>) {        let sum: i32 = v.iter().sum();        if sum < min {            v.to_mut().push(min - sum);        }    }    fn min_sum_refcell(min: i32, v: &RefCell<Vec<i32>>) {        let sum: i32 = v.borrow().iter().sum();        if sum < min {            v.borrow_mut().push(min - sum);        }    }    fn min_sum_cell(min: i32, v: &Cell<Vec<i32>>) {        let mut vec = v.take();        let sum: i32 = vec.iter().sum();        if sum < min {            vec.push(min - sum);        }        v.set(vec);    }
  1. These functions dynamically (based on incoming data) mutate a list of ...

Get Rust Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.