Advertisement
NLinker

RefCell vs normal refs

Oct 16th, 2017
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.61 KB | None | 0 0
  1. //https://play.rust-lang.org/?gist=c7fd2d14e8640ed21533ac27ecf1197e&version=stable
  2.  
  3. use std::cell::RefCell;
  4.  
  5. fn immutably_borrows(a: &i32) {
  6.     println!("a is {}", a);
  7. }
  8. fn mutably_borrows(a: &mut i32) {
  9.     *a +=1;
  10. }
  11.  
  12. fn demo_1(mut r: &mut i32) {
  13.     immutably_borrows(&r);
  14.     mutably_borrows(&mut r);
  15.     immutably_borrows(&r);
  16. }
  17.  
  18. fn demo_2(r: &RefCell<i32>) {
  19.     immutably_borrows(&r.borrow());
  20.     mutably_borrows(&mut r.borrow_mut());
  21.     immutably_borrows(&r.borrow());
  22. }
  23.  
  24. fn main() {
  25.     let mut data1 = 5;
  26.     let data2 = RefCell::new(5);
  27.     demo_1(&mut data1);
  28.     demo_2(&data2);
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement