什么是Cell
Cell 和 RefCell 都是基于 unsafeCell 来实现的.
Cell
所以Cell只能用于实现了Copy的类型
Cell与Refcell 是实现了内部可变性
展示
use std::cell::Cell;fn main(){let c = Cell::new("hello");let one = c.get();c.set("qwer");let two = c.get();println!("{},{}",one,two);}
实现机制
在使用set方法的时候 ,会调用replace方法进行替换,返回旧值,然后drop旧值
replace 调用了 mem下的replace 方法 使用ptr下的read跟write 进行操作.
使用Cell::from_mut解决借用冲突
fn is_even(i: i32) -> bool {i % 2 == 0}fn retain_even(nums: &mut Vec<i32>) {// let mut i = 0;// for num in nums.iter().filter(|&num| is_even(*num)) {// nums[i] = *num;// i += 1;// }// nums.truncate(i);let slice: &[Cell<i32>] = Cell::from_mut(&mut nums[..]).as_slice_of_cells();let mut i = 0;for num in slice.iter().filter(|num| is_even(num.get())) {slice[i].set(num.get());i += 1;}nums.truncate(i);}
