提交 2c02aab7 编写于 作者: J Jack Moffitt

Add cell#with_mut_ref for handling mutable references to the content.

上级 717ed51f
......@@ -73,6 +73,14 @@ fn with_ref<R>(&self, op: &fn(v: &T) -> R) -> R {
self.put_back(v);
r
}
// Calls a closure with a mutable reference to the value.
fn with_mut_ref<R>(&self, op: &fn(v: &mut T) -> R) -> R {
let mut v = self.take();
let r = op(&mut v);
self.put_back(v);
r
}
}
#[test]
......@@ -101,3 +109,21 @@ fn test_put_back_non_empty() {
let value_cell = Cell(~10);
value_cell.put_back(~20);
}
#[test]
fn test_with_ref() {
let good = 6;
let c = Cell(~[1, 2, 3, 4, 5, 6]);
let l = do c.with_ref() |v| { v.len() };
assert!(l == good);
}
#[test]
fn test_with_mut_ref() {
let good = ~[1, 2, 3];
let mut v = ~[1, 2];
let c = Cell(v);
do c.with_mut_ref() |v| { v.push(3); }
let v = c.take();
assert!(v == good);
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册