When I can use either Cell or RefCell, which should I choose?

I think it is important to take into account the other semantic differences between Cell and RefCell:

  • Cell provides you values, RefCell with references
  • Cell never panics, RefCell can panic

Let us imagine a situation where these differences matter:

let cell = Cell::new(foo);
{
    let mut value = cell.get();
    // do some heavy processing on value
    cell.set(value);
}

In this case, if we imagine some complex workflow with a lot of callback and that cell is part of a global state, it is possible that the contents of cell are modified as a side effect of the “heavy processing”, and these potential changes will be lost when value is written back in cell.

On the other hand, a similar code using RefCell:

let cell = RefCell::new(foo);
{
    let mut_ref = cell.borrow_mut().unwrap();
    // do some heavy processing on mut_ref
}

In this case, any modification of cell as a side-effect of the “heavy processing” is forbidden, and would result into a panic. You thus are certain that the value of cell will not change without using mut_ref

I would decide which to use depending of the semantics of the value it holds, rather than simply the Copy trait. If both are acceptable, then Cell is lighter and safer than the other, and thus would be preferable.

Leave a Comment