今天学习到RefCell这一章节,提到这么一段代码。小小的一段代码中有着不少的类型转换,我想在此做做总结。如果有错误或者不妥,请看到的同学帮我指出来。
//来自rust网站https://kaisery.github.io/trpl-zh-cn/ch15-05-interior-mutability.html
#[derive(Debug)]
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let value = Rc::new(RefCell::new(5));
let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a));
let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a));
*value.borrow_mut() += 10;
println!("a after = {:?}", a);
println!("b after = {:?}", b);
println!("c after = {:?}", c);
}
我想对*value.borrow_mut()
涉及到的类型转换做一下总结:
- 首先是value,它的type是
Rc<RefCell<i32>>
,通过automatic referencing变成&mut Rc<RefCell<i32>>
,再通过Rc<T>
的deref coercion 变成&mut RefCell<i32>
,然后通过automatic dereferencing 变成mut RefCell<i32>
。此时,我们对其callborrow_mut
method. - 当我们call完
borrow_mut
之后,我们得到了一个mut RefMut<i32>
的类型,我们从其开始后续转换。首先通过automatic referencing 变成&mut RefMut<T>
,然后通过RefMut<i32>
的deref coercion 变成&mut i32
。 - 最后,就是对其解引用,然后加10,再写回到原来的值当中。
由此看来,一句短短的代码,其中涉及的类型转换还是挺耐人寻味的。