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

前端 未结 3 1999
傲寒
傲寒 2020-12-01 17:40

From the std::cell documentation, I see that Cell is \"only compatible with types that implement Copy\". This means I must use RefCell

3条回答
  •  情歌与酒
    2020-12-01 18:11

    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.

提交回复
热议问题