Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can Cell in Rust only be used for Copy and not Clone types?

Tags:

The documentation of the Rust standard library states that Cell can be only used for Copy types and that in all other cases one should use RefCell, but does not explain exactly why.

After studying the documentation and the code of both Cell and RefCell, the only point where it seems to be important is the get function of Cell. If the value is a Copy type then one can just return such a copy. But why is a clone not good enough?

One could directly implement the set function on top of RefCell:

fn set<T>(r: &RefCell<T>, v: T) {
    *r.borrow_mut() = v
}

This only works as long as no one else is holding a reference to the value. But if the value can be cloned, one can just do that:

fn get<T: Clone>(r: &RefCell<T>) -> T {
    r.borrow().clone()
}

Having a type like Cell working with Clone types would avoid the overhead of the run-time borrow checking. Am I missing anything here?